Search code examples
ruby-on-railsmonkeypatching

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?


Solution

  • 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