user3023421
user3023421

Reputation: 363

Rails monkey patch gem issue

I am using https://github.com/mailboxer/mailboxer and I am trying to add my own photos to attach to each message

inside /config/initializes/extensions/mailboxer/message.rb

Mailboxer::Message.class_eval do
  has_many :photos, as: :imageable, :class_name => 'Photo'
end

This works great, except that it randomly throws an error:

undefined method `photos' for #<Mailboxer::Message:0x6eb0758>

When I start up the server for the first time it works. When I start modifying code (can be anything, nothing related to mailboxer) I get the error. I have to restart the server to get it working again.

I tried putting the file outside the initializes folder and adding an include path as the last line in config/boot.rb, same issue.

Any ideas as to why it is losing reference?

Upvotes: 0

Views: 151

Answers (1)

Matt Brictson
Matt Brictson

Reputation: 11082

When Rails detects your code has been modified, it "forgets" all the models, etc. it has auto-loaded, including Mailboxer::Message. The next time that model is used, it is reloaded from the mailboxer gem without your monkey patches.

To ensure your monkey patches "stick", I think you need to give Rails a hint that you want your code reapplied when it does a reload. Putting your patches in a to_prepare block may do the trick:

Rails.application.config.to_prepare do
  Mailboxer::Message.class_eval do
    has_many :photos, as: :imageable, :class_name => 'Photo'
  end
end

Upvotes: 2

Related Questions