From 0f633b385126930d498981db448c45ef23863439 Mon Sep 17 00:00:00 2001 From: Cadu Ribeiro Date: Fri, 24 Nov 2023 14:19:47 -0300 Subject: [PATCH] Change city_lookup to load all configured cities MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #67 There is a problem with city_lookup. It only loads the cities for the first statue you called `cities` on. This is because `cities` memoizes all the cities for the country, but `city_lookup` only loads the cities for the state, and doesn't get called again for the other states. Ex: having the following `db/cities-lookup.yml`: ```yaml BR: GO: "Mutunópolis": "Mutunópolis" ``` If I load first cities for other state, it does not include this missing city: ```shell bin/rails c CS.cities(:sp, :br) # loading another state first CS.cities(:go, :br).include?("Mutunópolis") ``` returned false but it should be true. If I load this state first, it works correctly ```shell bin/rails c CS.cities(:go, :br).include?("Mutunópolis") ``` This commit changes `city_lookup` to load all the cities for the country. --- lib/city-state.rb | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/lib/city-state.rb b/lib/city-state.rb index b8cb30e..49526e2 100644 --- a/lib/city-state.rb +++ b/lib/city-state.rb @@ -173,20 +173,23 @@ def self.cities(state, country = nil) end # Process lookup table - lookup = get_cities_lookup(country, state) + lookup = get_cities_lookup(country) if ! lookup.nil? - lookup.each do |old_value, new_value| - if new_value.nil? || self.blank?(new_value) - @cities[country][state].delete(old_value) - else - index = @cities[country][state].index(old_value) - if index.nil? - @cities[country][state][] = new_value + lookup.each do |state, new_values| + new_values.each do |old_value, new_value| + if new_value.nil? || self.blank?(new_value) + @cities[country][state].delete(old_value) else - @cities[country][state][index] = new_value + index = @cities[country][state].index(old_value) + if index.nil? + @cities[country][state] << new_value + else + @cities[country][state][index] = new_value + end end end end + @cities[country][state] = @cities[country][state].sort # sort it alphabetically end end @@ -210,7 +213,7 @@ def self.set_countries_lookup_file(filename) @countries_lookup = nil end - def self.get_cities_lookup(country, state) + def self.get_cities_lookup(country) # lookup file not loaded if @cities_lookup.nil? @cities_lookup_fn = DEFAULT_CITIES_LOOKUP_FN if @cities_lookup_fn.nil? @@ -220,8 +223,8 @@ def self.get_cities_lookup(country, state) @cities_lookup.each { |key, value| @cities_lookup[key] = self.symbolize_keys(value) } # force states to be symbols end - return nil if ! @cities_lookup.key?(country) || ! @cities_lookup[country].key?(state) - @cities_lookup[country][state] + return nil if ! @cities_lookup.key?(country) + @cities_lookup[country] end def self.get_states_lookup(country)