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!