Aug 302010
 

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.

 Posted by at 5:49 pm  Tagged with:

 Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.