Paul
Paul

Reputation: 1031

ActiveRecord Models - adding custom methods

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

Upvotes: 0

Views: 2119

Answers (3)

Yehuda Katz
Yehuda Katz

Reputation: 28703

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.

Upvotes: 0

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94123

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

Upvotes: 1

DanSingerman
DanSingerman

Reputation: 36502

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

Upvotes: 4

Related Questions