Reputation: 1867
I have built a rails plugin and it has a requirement of building some files to work correctly. A user can manually kick this off as a rake task, but for convenience in development, I would like to add the option of rerunning this build whenever they refresh their browsers.
Just to be clear, I do not want to reLOAD the plugin every refresh, nor do I want to reload any other ruby file. I would like to run some arbitrary ruby code every time Rails decides to reload it's libraries.
Upvotes: 0
Views: 160
Reputation: 1867
I came across this solution which is a bit more to the point.
ActionDispatch::Callbacks.to_prepare do
Rails.logger.warn "Look at me I'm updating!"
end
Upvotes: 0
Reputation: 3868
First solution:
You have to add:
config.autoload_paths += %W(#{config.root}/lib)
In your Application class in config/application.rb
Please refer this link https://rails.lighthouseapp.com/projects/8994/tickets/5218-rails-3-rc-does-not-autoload-from-lib
Another One:
It is more useful try it,
New file: config/initializers/reload_lib.rb
if Rails.env == "development"
lib_reloader = ActiveSupport::FileUpdateChecker.new(Dir["lib/**/*"]) do
Rails.application.reload_routes! # or do something better here
end
ActionDispatch::Callbacks.to_prepare do
lib_reloader.execute_if_updated
end
end
It's disgusting but it's a hack. There might be a better way to trigger a full reload, but this works for me. My specific use case was a Rack app mounted to a Rails route so I needed it to reload as I worked on it in development.
Basically what it does is it checks if any files in /lib
have changed (modified timestamp) since last loaded and then triggers a reload if they change.
I might also mention I have this in my config/application.rb
config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]
Which just by default makes sure everything in my lib directory gets loaded.
Upvotes: 2