views:

130

answers:

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!

+2  A: 

You can either a) do something to similar to application_controller and create a model class from which others can subclass or b) use a module.

+1  A: 

There are a number of ways you can share methods between 2 model classes.

  • Use inheritance if the models are related to each other, e.g. a shared parent class that contains the methods, or one subclasses the other that contains the methods.
  • Use modules/mixins that can be shared among multiple models
marklai
`Turn those methods into helper methods that both models have access to` - I thought models didn't have access to helper methods. How is that possible (seems like the cleanest method for what I'm trying to do)
yuval
You're right. I was thinking utility methods, not "helper methods" in the rails sense. So the mixin approach would be more useful than utility methods.
marklai
+4  A: 

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!
Josh
thank you! that's what I ended up using
yuval
dude. It's all about the lib dir. I've started to put more code there and it is just convenient place to organize things.
Joseph Silvashy