views:

150

answers:

2

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
+2  A: 

Something like that:

def attr
  value = read_attribute :attr
  value = modify(value)
  write_attribute :attr, value
  save
  value
end
neutrino
+1  A: 

Neutrino's method is good if you want to save a modified value back to the database each time you get the attribute. This not recommended since it will execute an extra database query every time you try to read the attribute even if it has not changed.

If you simply want to modify the attribute (such as capitalizing it for example) you can just do the following:

 def attr
   return read_attribute(:attr).capitalize #(or whatever method you wish to apply to the value)
 end
Gdeglin
The question itself is actually a bit unclear in what it's meant to do when you "modify" the value. If you don't want to store it, then obviously there's no need to save the model :)
neutrino
def attrself[:attr].capitalizeendwould also work
psyho