views:

371

answers:

3

Hi,

I have 10 models and 3 of them need some additional custom methods which happen to be:

has_staged_version?
apply_staged_version
discard_staged_version

I want to define these methods once.

I could create a custom subclass of ActiveRecord:Base, define the methods there, and have my 3 models inherit from it. But is there a more "Ruby/Rails" way to achieve this?

Cheers

+3  A: 

Use a module as a mixin.

See http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/

e.g.

in /lib have

module StagedVersionStuff

  def has_staged_version?

  end

  def apply_staged_version

  end

  def discard_staged_version

  end
end

and then in the models you want to have these methods you have

include StagedVersionStuff

after the Class declaration

DanSingerman
+1  A: 

You could create a module and have your classes include it:

module StagedVersionMethods
  def has_staged_version?
  end

  def apply_staged_version
  end

  def discard_staged_version
  end
end

Model.send :include, StagedVersionMethods
Daniel Vandersluis
Great thanks - this is the sort of thing I was after.
Paul
A: 

What do your classes do? The choice of whether to use a subclass or module is more a question of semantics on the basis of what the classes themselves are.

Yehuda Katz