Lets say you have a widget model in Ruby on Rails.  Your database table contains a field called “name”.  Let’s say you want to add something to this field in your model.  You need a specialized def in order to do this.. you need to use write_attribute and read_attribute methods.

Here is an example where I override the Rails ActiveRecord model attribute setter. This will append a test string onto the name:

class Widget < ActiveRecord::Base
  def name=(name)
    write_attribute(:name,"#{name} - test")
  end
end

You can also do this with the read_attribute method and it works the opposite way… instead of operating on the setter, you operate on the getter.