NullVoxPopuli
NullVoxPopuli

Reputation: 65093

Ruby on Rails: shared method between models

If a few of my models have a privacy column, is there a way I can write one method shared by all the models, lets call it is_public?

so, I'd like to be able to do object_var.is_public?

Upvotes: 25

Views: 12854

Answers (2)

jigfox
jigfox

Reputation: 18185

One possible way is to put shared methods in a module like this (RAILS_ROOT/lib/shared_methods.rb)

module SharedMethods
  def is_public?
    # your code
  end
end

Then you need to include this module in every model that should have these methods (i.e. app/models/your_model.rb)

class YourModel < ActiveRecord::Base
  include SharedMethods
end

UPDATE:

In Rails 4 there is a new way to do this. You should place shared Code like this in app/models/concerns instead of lib

Also you can add class methods and execute code on inclusion like this

module SharedMethods
  extend ActiveSupport::Concern

  included do
    scope :public, -> { where(…) }
  end

  def is_public?
    # your code
  end

  module ClassMethods
    def find_all_public
      where #some condition
    end
  end
end

Upvotes: 53

zetetic
zetetic

Reputation: 47548

You can also do this by inheriting the models from a common ancestor which includes the shared methods.

class BaseModel < ActiveRecord::Base
  def is_public?
    # blah blah
   end
end

class ChildModel < BaseModel
end

In practice, jigfox's approach often works out better, so don't feel obligated to use inheritance merely out of love for OOP theory :)

Upvotes: 6

Related Questions