Skip to content

Instantly share code, notes, and snippets.

@maxim
Created July 26, 2009 17:48
Show Gist options
  • Save maxim/155870 to your computer and use it in GitHub Desktop.
Save maxim/155870 to your computer and use it in GitHub Desktop.
# When you have duplication like this
def base_price(options = {})
PriceFormatter::Formatter.format(super, options)
end
def price(options = {})
PriceFormatter::Formatter.format(base_price * quantity, options)
end
# You can change it into declarative style like this
formats_as_price :base_price, :price
def price
base_price * quantity
end
# Much cleaner, but... Doesn't work in case of #price method above.
# Even though all the standard attribute methods such as base_price get overridden,
# my own defined #price method doesn't. Here's the plugin code.
module Helper
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def formats_as_price(*meths)
meths.each do |meth|
define_method meth do |*args|
options = args.extract_options!
PriceFormatter::Formatter.format(super, options)
end
end
end
end
end
ActiveRecord::Base.send(:include, PriceFormatter::Helper)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment