From 485449e289d184b32cb16a60c59a1868b4d97b52 Mon Sep 17 00:00:00 2001 From: Pau Perez Date: Mon, 8 Mar 2021 10:12:56 +0100 Subject: [PATCH] Fix Money gem deprecation warning with :format This removes millions of deprecation warnings like the following ``` [DEPRECATION] `symbol_position: :before` is deprecated - you can replace it with `format: %u %n` ``` from the build. It gets printed every time a `Spree::Money` is instantiated. This should result in a non-negligible speed up of the test suite. --- lib/spree/money.rb | 40 ++++++++++++++++++++++++++++-------- spec/lib/spree/money_spec.rb | 5 +++++ 2 files changed, 36 insertions(+), 9 deletions(-) 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