Permalink
Browse files

Add global settings for money object formatted output

- Use no_cents_if_whole, symbol flags to handle the corresponding option
  of Money#format method.
- A user may override the global settings by providing them explicitly as
  hash params in Money#format calls.
  • Loading branch information...
1 parent 73b35b2 commit e66ebf789cc5c7d5157bc04c7ff7d18562f49ed8 @alup alup committed Jan 28, 2013
Showing with 65 additions and 0 deletions.
  1. +1 −0 lib/money-rails.rb
  2. +7 −0 lib/money-rails/configuration.rb
  3. +23 −0 lib/money-rails/money.rb
  4. +34 −0 spec/configuration_spec.rb
View
@@ -1,5 +1,6 @@
require "money"
require "money-rails/configuration"
+require "money-rails/money"
require "money-rails/version"
require 'money-rails/hooks'
@@ -50,5 +50,12 @@ def register_currency=(currency_options)
mattr_accessor :currency_column
@@currency_column = { postfix: '_currency', type: :string, null: false, default: 'USD', present: true }
+
+ # Use nil values to ignore defaults
+ mattr_accessor :no_cents_if_whole
+ @@no_cents_if_whole = nil
+
+ mattr_accessor :symbol
+ @@symbol = nil
end
end
@@ -0,0 +1,23 @@
+require "active_support/core_ext/module/aliasing.rb"
+require "active_support/core_ext/hash/reverse_merge.rb"
+
+class Money
+
+ def format_with_settings(*rules)
+ rules = normalize_formatting_rules(rules)
+
+ # Apply global defaults for money only for non-nil values
+ # TODO: Add here more setting options
+ defaults = {
+ no_cents_if_whole: MoneyRails::Configuration.no_cents_if_whole,
+ symbol: MoneyRails::Configuration.symbol
+ }.reject { |k,v| v.nil? }
+
+ rules.reverse_merge!(defaults)
+
+ format_without_settings(rules)
+ end
+
+ alias_method_chain :format, :settings
+
+end
@@ -16,5 +16,39 @@
Money.us_dollar(100).exchange_to("CAD").should == Money.new(124, "CAD")
Money.ca_dollar(100).exchange_to("USD").should == Money.new(80, "USD")
end
+
+ it "sets no_cents_if_whole value for formatted output globally" do
+ value = Money.new(12345600, "EUR")
+ mark = Money::Currency.find(:eur).decimal_mark
+ value.format.should =~ /#{mark}/
+
+ MoneyRails.no_cents_if_whole = true
+ value.format.should_not =~ /#{mark}/
+ value.format(no_cents_if_whole: false).should =~ /#{mark}/
+
+ MoneyRails.no_cents_if_whole = false
+ value.format.should =~ /#{mark}/
+ value.format(no_cents_if_whole: true).should_not =~ /#{mark}/
+
+ # Reset global setting
+ MoneyRails.no_cents_if_whole = nil
+ end
+
+ it "sets symbol for formatted output globally" do
+ value = Money.new(12345600, "EUR")
+ symbol = Money::Currency.find(:eur).symbol
+ value.format.should =~ /#{symbol}/
+
+ MoneyRails.symbol = false
+ value.format.should_not =~ /#{symbol}/
+ value.format(symbol: true).should =~ /#{symbol}/
+
+ MoneyRails.symbol = true
+ value.format.should =~ /#{symbol}/
+ value.format(symbol: false).should_not =~ /#{symbol}/
+
+ # Reset global setting
+ MoneyRails.symbol = nil
+ end
end
end

0 comments on commit e66ebf7

Please sign in to comment.