Here’s a common pattern and good rails thing to know about: read_attribute(:symbol)

Basically what it does is read the attribute from the object’s database field, even if you have over-ridden the name of that attribute with a virtual attribute of the same name.

# == Schema Information
#
# Table name: some_things
#
# id            :integer(4)   not null, primary key
# value          :string(255)

class SomeThing
 # attribute reader method that is the same name
 # as an existing field on this table (in the database)

 def value
  if (something_is_true)
   “not showing you the real value”
  else
   # return the data from the field in value
   read_attribute(:value)
  end
 end

end

Obviously the thing to notice is that if you didn’t use read_attribute(:value) above and instead put a call to “value” (as you would with normal attributes), it would simply call this method again creating an infinite loop. It’s an obscure pattern but it’s an important one to know about.

By Jason

Leave a Reply

Your email address will not be published. Required fields are marked *