Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

custom attr_reader in rails

Mostly in rails if you write my_obj.attr it looks up attr in the database and reports it back. How do you create a custom def attr method that internally queries the database for attr, modifies it and returns? In other words, what's the missing piece here:

# Within a model. Basic attr_reader method, will later modify the body.
def attr
  get_from_database :attr   # <-- how do I get the value of attr from the db?
end
like image 958
Peter Avatar asked Mar 09 '26 02:03

Peter


1 Answers

Something like that:

def attr
  value = read_attribute :attr
  value = modify(value)
  write_attribute :attr, value
  save
  value
end
like image 57
alex.zherdev Avatar answered Mar 10 '26 14:03

alex.zherdev