From d2717849d12e17aeb8eb25913292f5d5dd867f24 Mon Sep 17 00:00:00 2001 From: Anthony Dmitriyev Date: Sun, 12 Jul 2015 22:09:15 +0100 Subject: [PATCH] Refactor Currency#new method --- lib/money/currency.rb | 10 +++++----- spec/currency_spec.rb | 10 +++++++++- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/lib/money/currency.rb b/lib/money/currency.rb index f339bfc774..767fe2cfeb 100644 --- a/lib/money/currency.rb +++ b/lib/money/currency.rb @@ -18,6 +18,7 @@ class Currency # Keeping cached instances in sync between threads @@mutex = Mutex.new + @@instances = {} # Thrown when a Currency has been registered without all the attributes # which are required for the current action. @@ -34,18 +35,17 @@ def initialize(method, currency, attribute) class UnknownCurrency < ArgumentError; end class << self - alias_method :original_new, :new def new(id) id = id.to_s.downcase unless stringified_keys.include?(id) raise UnknownCurrency, "Unknown currency '#{id}'" end - @@mutex.synchronize { instances[id] } || super + _instances[id] || @@mutex.synchronize { _instances[id] ||= super } end - def instances - @instances ||= Hash.new { |h, k| h[k] = original_new(k) } + def _instances + @@instances end # Lookup a currency with given +id+ an returns a +Currency+ instance on @@ -168,7 +168,7 @@ def stringified_keys # @option delimiter [String] character between each thousands place def register(curr) key = curr.fetch(:iso_code).downcase.to_sym - @@mutex.synchronize { instances.delete(key.to_s) } + @@mutex.synchronize { _instances.delete(key.to_s) } @table[key] = curr @stringified_keys = stringify_keys end diff --git a/spec/currency_spec.rb b/spec/currency_spec.rb index 6599de0eb6..50d1f340e8 100644 --- a/spec/currency_spec.rb +++ b/spec/currency_spec.rb @@ -170,7 +170,8 @@ def to_s describe "#initialize" do - before { Currency.instances.clear } + before { Currency._instances.clear } + it "lookups data from loaded config" do currency = Currency.new("USD") expect(currency.id).to eq :usd @@ -185,6 +186,13 @@ def to_s expect(currency.smallest_denomination).to eq 1 end + it 'caches instances' do + currency = Currency.new("USD") + + expect(Currency._instances.length).to eq 1 + expect(Currency._instances["usd"].object_id).to eq currency.object_id + end + it "raises UnknownCurrency with unknown currency" do expect { Currency.new("xxx") }.to raise_error(Currency::UnknownCurrency, /xxx/) end