diff --git a/lib/spree/money.rb b/lib/spree/money.rb index 8ff14ce203..d0d3e581e9 100644 --- a/lib/spree/money.rb +++ b/lib/spree/money.rb @@ -10,15 +10,12 @@ module Spree def initialize(amount, options = {}) @money = ::Monetize.parse([amount, (options[:currency] || Spree::Config[:currency])].join) - @options = {} - @options[:with_currency] = Spree::Config[:display_currency] - @options[:symbol_position] = Spree::Config[:currency_symbol_position].to_sym - @options[:no_cents] = Spree::Config[:hide_cents] - @options[:decimal_mark] = Spree::Config[:currency_decimal_mark] - @options[:thousands_separator] = Spree::Config[:currency_thousands_separator] - @options.merge!(options) - # Must be a symbol because the Money gem doesn't do the conversion - @options[:symbol_position] = @options[:symbol_position].to_sym + + if options.key?(:symbol_position) + options[:format] = position_to_format(options.delete(:symbol_position)) + end + + @options = defaults.merge(options) end # Return the currency symbol (on its own) for the current default currency @@ -47,5 +44,30 @@ module Spree def ==(other) @money == other.money end + + private + + def defaults + { + with_currency: Spree::Config[:display_currency], + no_cents: Spree::Config[:hide_cents], + decimal_mark: Spree::Config[:currency_decimal_mark], + thousands_separator: Spree::Config[:currency_thousands_separator], + format: position_to_format(Spree::Config[:currency_symbol_position]) + } + end + + def position_to_format(position) + return if position.nil? + + case position.to_sym + when :before + '%u%n' + when :after + '%n %u' + else + raise 'Invalid symbol position' + end + end end end diff --git a/spec/lib/spree/money_spec.rb b/spec/lib/spree/money_spec.rb index 6454be64fc..9b7ad8e534 100644 --- a/spec/lib/spree/money_spec.rb +++ b/spec/lib/spree/money_spec.rb @@ -82,6 +82,11 @@ describe Spree::Money do money = Spree::Money.new(10, html: false) expect(money.to_s).to eq("10.00 $") end + + it 'raises with invalid position' do + expect { Spree::Money.new(10, symbol_position: 'invalid') } + .to raise_error('Invalid symbol position') + end end context "EUR" do