I have a couple of methods I'd like to share between models rather than copying and pasting them. In a controller, I can do this by putting the methods in application_controller.rb which automatically gets included in every controller. Is there a similar thing for models?
Thanks!
You can create a file called functionality.rb
or something similar in the lib
directory of your Rails app. Make the file named after the module to autoload it when Rails starts. For example, if I wanted to add flagging to multiple models, I'd create a file called lib/flagging.rb
, and it would look like this:
module Flagging
# Flags an object for further review
def flag!
self.update_attribute(:flagged, true)
end
# Clears all flags on an object
def deflag!
self.update_attribute(:flagged, false)
end
end
In every model I wanted to add this functionality to, I'd do the following:
class Foo < ActiveRecord::Base
include Flagging
end
I'd then be able to do something like:
foo = Foo.create
foo.flag!
The top solution above worked for me. In Rails 3 I found I also had to update the application.rb file with: config.autoload_paths += Dir["#{config.root}/lib/**/"]
as answered here: Best way to load module/class from lib folder in Rails 3?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With