Skip to content

Instantly share code, notes, and snippets.

@cherring
Created September 15, 2009 01:40
Show Gist options
  • Save cherring/187056 to your computer and use it in GitHub Desktop.
Save cherring/187056 to your computer and use it in GitHub Desktop.
class SomeClass < ActiveRecord::Base
include NumberToCurrency
end
module NumberToCurrency
def self.included(base)
base.extend ClassMethods
end
module ClassMethods
def number_to_currency(number, options = {})
options.symbolize_keys!
defaults = I18n.translate('number.format''number.format', :locale => options[:locale], :raise => true) rescue {}
currency = I18n.translate('number.currency.format''number.currency.format', :locale => options[:locale], :raise => true) rescue {}
defaults = defaults.merge(currency)
precision = options[:precision] || defaults[:precision]
unit = options[:unit] || defaults[:unit]
separator = options[:separator] || defaults[:separator]
delimiter = options[:delimiter] || defaults[:delimiter]
format = options[:format] || defaults[:format]
separator = '' if precision == 0
begin
format.gsub(/%n/, number_with_precision(number,
:precision => precision,
:delimiter => delimiter,
:separator => separator)
).gsub(/%u/, unit)
rescue
number
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment