Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Can I modify the value of an attribute before it is called?

Let's say I have this model named Product with a field named brand. Suppose the values of brand are stored in the format this_is_a_brand. Can I define a method in the model (or anywhere else) that allows me to modify the value of brand before it is called. For example, if I call @product.brand, I want to get This is a Brand, instead of this_is_a_brand.

like image 976
sker Avatar asked Oct 08 '08 07:10

sker


1 Answers

I would recommend using the square bracket syntax ([] and []=) instead of read_attribute and write_attribute. The square bracket syntax is shorter and designed to wrap the protected read/write_attribute methods.

def brand
  original = self[:brand]
  transform(original)
end

def brand=(b)
  self[:brand] = reverse_transform(b)
end
like image 70
two-bit-fool Avatar answered Nov 03 '22 21:11

two-bit-fool