csi
csi

Reputation: 9328

Overriding Instance Method in Rails Library

This seems like a monkey patch. How can I improve it?

Trying to override the deliver_now instance method from the ActionMailer::MessageDelivery class. The below code works.

However, is there a way I can achieve this more elegantly say through class inheritance or some other way? The end code is used in a custom ActionMailer mailer.

module MyModule
  class Ses 

    ActionMailer::MessageDelivery.class_eval do
      def deliver_now!
        puts self.to
        puts self.subject
      end
    end
    ...
  end
end

Note: I've seen these similar questions one & two but they do not address this issue.

Upvotes: 1

Views: 393

Answers (1)

yez
yez

Reputation: 2378

You might look into Ruby's refinements

An example refinement:

module MyMessageRefinement
  refine(ActionMailer::MessageDelivery) do
    def deliver_now!
      puts self.to
      puts self.subject
    end
  end    
end

Then in your class:

module MyModule
  class Ses 
    using MyMessageRefinement
  end
end

Upvotes: 3

Related Questions