views:

54

answers:

3

By default, ActiveRecord takes all fields from the corresponding database table and creates public attributes for all of them.

I think that it's reasonable not to make all attributes in a model public. Even more, exposing attributes that are meant for internal use clutters the model's interface and violates the incapsulation principle.

So, is there a way to make some of the attributes literally private?

Or, maybe I should move on to some other ORM?

+1  A: 

well, you could always override the methods...

class YourModel < ActiveRecord::Base

  private

  def my_private_attribute
    self[:my_private_attribute]
  end

  def my_private_attribute=(val)
    self[:my_private_attribute] = val
  end

end
jordinl
A: 

You can make an existing method private:

YourClass.send(:private, :your_method)
Mark Thomas
+1  A: 

Jordini was most of the way there

Most of active_record happens in method_missing. If you define the method up front, it won't hit method_missing for that method, and use yours in stead (effectively overwriting, but not really)

class YourModel < ActiveRecord::Base

  private

  def my_private_attribute
    self[:my_private_attribute]
  end

  def my_private_attribute=(val)
    write_attribute :my_private_attribute, val
  end

end
Matt Briggs