Skip to content

Commit

Permalink
Change city_lookup to load all configured cities
Browse files Browse the repository at this point in the history
Closes thecodecrate#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.
  • Loading branch information
duduribeiro committed Nov 24, 2023
1 parent b6912a4 commit 0f633b3
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions lib/city-state.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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?
Expand All @@ -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)
Expand Down

0 comments on commit 0f633b3

Please sign in to comment.