Usually alias_method_chain does a great job when you need to monkey patch some code. One limitation, however, is that both the original method and the hack method must be defined before using alias_method_chain. This is rarely an issue, but it does come into play if you ever want to chain methods to an ActiveRecord column getter/setter. These methods are added on the fly, so you have no access to them within your model class.
Now you can simply use delayed_method_chain:
# has a :price column
class Product < ActiveRecord::Base
require 'delayed_method_chain'
delayed_method_chain :price=, :formatting
# quick formatting
def price_with_formatting=(amt)
price_without_formatting = amt.to_s.gsub(/[^0-9\.]/, '').to_f.round(2)
end
end
You can download the code, or alter the gist on GitHub if you have ideas on how to improve it!
Posted by chrisjpowers