sker
sker

Reputation: 18362

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.

Upvotes: 6

Views: 5372

Answers (4)

frankpinto
frankpinto

Reputation: 166

As the last answer was posted 7 years ago, I'll contribute what the Rails API currently suggests.

def brand
  super.humanize
end

Humanize turns 'this_is_a_brand' to 'This is a brand'

Upvotes: 1

two-bit-fool
two-bit-fool

Reputation: 5088

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

Upvotes: 12

tomafro
tomafro

Reputation: 5846

Rather than accessing @attributes directly, you should use read_attribute and 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

Upvotes: 9

Josh Moore
Josh Moore

Reputation: 13558

In your model you can override the method call brand.

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

This will allow it to be stored as this_is_a_brand. But, it will be returned as "this is a brand".

Upvotes: 0

Related Questions