views:

42

answers:

2

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?

+4  A: 

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 two include this module in every model that should have this methods (i.e. app/models/your_model.rb)

class YourModel < ActiveRecord::Base
  include SharedMethods
end
jigfox
but I would need to pass a variable telling the method what class i'm using...
DerNalia
self.class would give you whatever the class is in the context of that method being called. So, for instance, if you did YourModel.new.is_public?, self.class would be YourModel.
lambdabutz
+2  A: 

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

zetetic