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

Say I have this model called Product with a field called brand. Suppose brand values ​​are stored in the format this_is_a_brand. Can I define a method in the model (or elsewhere) that allows me to modify the brand value before it is called. For example, if I call @ product.brand, I want to get this brand, not this_is_a_brand.

+5
source share
4 answers

I would recommend using the syntax square brackets ( []and []=) instead of read_attributeand write_attribute. The square bracket syntax is shorter and is intended to carry the protected read / write_attribute methods .

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

def brand=(b)
  self[:brand] = reverse_transform(b)
end
+9
source

Instead of directly accessing @attributes, you should use read_attributeand write_attribute:

def brand
  b = read_attribute(:brand) 
  b && b.transform_in_some_way
end

def brand=(b)
  b && b.transform_in_some_way
  write_attribute(:brand, b)
end
+7
source

7 , , Rails API.

def brand
  super.humanize
end

Humanize 'this_is_a_brand' ' '

+1

brand.

def brand
#code to modify the value that is stored in brand
return modified_brand
end

this_is_a_brand. " ".

0

All Articles