Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 431
NullVoxPopuli Avatar asked Aug 11 '10 18:08

NullVoxPopuli


2 Answers

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
like image 59
jigfox Avatar answered Nov 15 '22 17:11

jigfox


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 :)

like image 6
zetetic Avatar answered Nov 15 '22 17:11

zetetic