From 72046b1e8d45e2ae32c8a36cb050f7cbf831cb02 Mon Sep 17 00:00:00 2001 From: sota-horiuchi Date: Tue, 26 Mar 2024 18:00:16 +0900 Subject: [PATCH] Refactore: method to get current locale --- lib/ingreedy/amount_parser.rb | 2 +- lib/ingreedy/dictionary.rb | 5 +++-- lib/ingreedy/dictionary_collection.rb | 18 +++++------------- lib/ingreedy/root_parser.rb | 2 +- 4 files changed, 10 insertions(+), 17 deletions(-) diff --git a/lib/ingreedy/amount_parser.rb b/lib/ingreedy/amount_parser.rb index d6f291e..20f5de1 100644 --- a/lib/ingreedy/amount_parser.rb +++ b/lib/ingreedy/amount_parser.rb @@ -64,7 +64,7 @@ class AmountParser < Parslet::Parser private def current_locale - Ingreedy.dictionaries.current_locale + Ingreedy.dictionaries.current.locale end def word_digits diff --git a/lib/ingreedy/dictionary.rb b/lib/ingreedy/dictionary.rb index 3b329fe..20b113d 100644 --- a/lib/ingreedy/dictionary.rb +++ b/lib/ingreedy/dictionary.rb @@ -1,14 +1,15 @@ module Ingreedy class Dictionary - attr_reader :units, :numbers, :prepositions, :range_separators + attr_reader :units, :numbers, :prepositions, :range_separators, :locale attr_reader :imprecise_amounts - def initialize(units:, numbers: {}, prepositions: [], range_separators: %w{- ~}, imprecise_amounts: []) + def initialize(units:, numbers: {}, prepositions: [], range_separators: %w{- ~}, imprecise_amounts: [], locale: nil) @units = units @numbers = sort_by_length(numbers) @prepositions = prepositions @range_separators = range_separators @imprecise_amounts = imprecise_amounts + @locale = locale end # https://en.wikipedia.org/wiki/Number_Forms diff --git a/lib/ingreedy/dictionary_collection.rb b/lib/ingreedy/dictionary_collection.rb index 167ca45..ed47c51 100644 --- a/lib/ingreedy/dictionary_collection.rb +++ b/lib/ingreedy/dictionary_collection.rb @@ -8,29 +8,21 @@ def initialize end def []=(locale, attributes) - @collection[locale] = Dictionary.new(**attributes) + @collection[locale] = Dictionary.new(locale:, **attributes) end def current - fetch_dictionary(current_locale) - end - - def current_locale - find_locale - end - - private - - def find_locale candidate_locales.each do |locale| if dictionary = fetch_dictionary(locale) - return locale + return dictionary end end raise "No dictionary found for locales: #{candidate_locales}" end + private + def candidate_locales Array(Ingreedy.locale || i18n_gem_locales || :en) end @@ -46,7 +38,7 @@ def i18n_gem_locales end def fetch_dictionary(locale) - @collection[locale] ||= Dictionary.new **load_yaml(locale) + @collection[locale] ||= Dictionary.new(locale:, **load_yaml(locale)) rescue Errno::ENOENT end diff --git a/lib/ingreedy/root_parser.rb b/lib/ingreedy/root_parser.rb index 1f30219..ec4b884 100644 --- a/lib/ingreedy/root_parser.rb +++ b/lib/ingreedy/root_parser.rb @@ -126,7 +126,7 @@ def parse attr_reader :original_query def current_locale - Ingreedy.dictionaries.current_locale + Ingreedy.dictionaries.current.locale end def imprecise_amounts