0

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 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.