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

attributes, model, ruby, ruby-on-rails

Solution

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

Problem

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.

Original source