Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share code across models? (Rails 2.3)

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!

like image 670
Yuval Karmi Avatar asked Feb 28 '10 22:02

Yuval Karmi


2 Answers

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!
like image 191
Josh Delsman Avatar answered Oct 08 '22 09:10

Josh Delsman


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?

like image 21
Ben Morris Avatar answered Oct 08 '22 11:10

Ben Morris