Nicolas Maloeuvre
Nicolas Maloeuvre

Reputation: 3169

How to monkey patch in Ruby on Rails

I want to add a method to ActiveStorage::Blob. I have this:

config/initializers/active_storage_cached_urls.rb

module ActiveStorageBlobCachedUrl
  def direct_url
    xxx || self.service_url
  end
end

end of config/environment.rb

ActiveStorage::Blob.include ActiveStorageBlobCachedUrl

I launched rails s in development, and it works. Then I updated one ruby file, such as a model, and I got an error: undefined method 'direct_url....

I guess something is reloaded without my monkey patch. What am I missing in order to have my monkey patch also reloaded?

Upvotes: 3

Views: 797

Answers (2)

Nicolas Maloeuvre
Nicolas Maloeuvre

Reputation: 3169

put this in a file in initializers/

module ActiveStorageBlobCachedUrl
  def direct_url
    # xx
  end
end


ActiveSupport::Reloader.to_prepare do
  ActiveStorage::Blob.include ActiveStorageBlobCachedUrl
end

Upvotes: 1

Nicolas Maloeuvre
Nicolas Maloeuvre

Reputation: 3169

This is not an optimal solution, but when I put the code in environment.rb or in lib/.rb or in config/initializers/.rb, then I have the error.

If I put it one model file, then it works.

app/models/random_model.rb

ActiveStorage::Blob.include ActiveStorageBlobCachedUrl
ActiveStorage::Variant.include ActiveStorageVariantCachedUrl

class RandomModel < ApplicationRecord
  xxx
end

Upvotes: 1

Related Questions