Created
February 23, 2009 01:37
-
-
Save johnbender/68726 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#Make it possile for euro symbol to display properly | |
#DANGEROUS, AS IT BREAKS RUBY STRING METHODS | |
## | |
$KCODE = "u" | |
## | |
class Currency | |
#format hash: containing the symbol, thousands (and higher) delimiter and decimal | |
#usd_rate: some ratio when compaired to the dollar (ie the dollar is always 1) | |
attr_accessor :format, :usd_rate | |
#define the format and the rate in terms of us dollars | |
def initialize(format, usd_rate) | |
@format, @usd_rate = format, usd_rate | |
end | |
#add the commas (or periods depending) to the integer part of the amount | |
#add the period (or comma depending) to the decimal portion | |
def format(amount) | |
amtstr = '%.2f' % amount | |
int, dec = amtstr.split(".") | |
@format[:sym] + int.reverse.gsub(/(\d{3})(?=\d)/, '\&' + @format[:thou]).reverse + @format[:dec] + dec | |
end | |
end | |
#converts amounts of currency to and from those currencies available in the currencies hash | |
# | |
#>> c = CurrencyConverter.new | |
#>> c.us_to_euro(10000) | |
#=> "€7.870,00" | |
class CurrencyConverter | |
#the list of currencies available for use | |
attr_accessor :currencies | |
#define default currencies for use | |
def initialize | |
@currencies = { "us" => Currency.new({:sym => "$" , :thou => "," , :dec => "."}, 1), | |
"euro" => Currency.new({:sym => "€" , :thou => "." , :dec => ","}, 0.787)} | |
end | |
#convert based on the currency name | |
def convert(from, to, amount) | |
value = amount * @currencies[to].usd_rate/@currencies[from].usd_rate | |
@currencies[to].format(value) | |
rescue NoMethodError | |
puts "Oops! You did something funny, try again!" | |
end | |
#catch any currency_to_currency method calls | |
def method_missing(method, *args) | |
if method.to_s =~ /^([a-z]+)_to_([a-z]+)$/ | |
convert($1, $2, args.first) | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment