Class: Cdek::CityResolver

Inherits:
Object
  • Object
show all
Defined in:
lib/cdek/city_resolver.rb

Overview

Resolves a human-readable city name to a CDEK city record — both the CDEK city code and the city coordinates — in one API-backed, cached lookup.

This is intentionally small and API-backed: host applications can pass user-entered city names to the widget proxy without duplicating lookup logic or loading all delivery points for the whole country. The widget proxy uses #code to filter offices, while the widget helper uses #coordinates to center the map on the chosen city (passing coordinates to the JS widget instead of a name avoids a flaky async geocode that could otherwise drop the map back to its built-in default center).

Constant Summary collapse

DEFAULT_COUNTRY_CODES =
"RU"
CACHE_EXPIRES_IN =
43_200

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, client: Cdek.client, country_codes: DEFAULT_COUNTRY_CODES, cache: default_cache) ⇒ CityResolver

Returns a new instance of CityResolver.



28
29
30
31
32
33
# File 'lib/cdek/city_resolver.rb', line 28

def initialize(name, client: Cdek.client, country_codes: DEFAULT_COUNTRY_CODES, cache: default_cache)
  @name = name
  @client = client
  @country_codes = country_codes
  @cache = cache
end

Class Method Details

.call(name, **options) ⇒ Object



19
20
21
# File 'lib/cdek/city_resolver.rb', line 19

def call(name, **options)
  new(name, **options).code
end

.coordinates(name, **options) ⇒ Object



23
24
25
# File 'lib/cdek/city_resolver.rb', line 23

def coordinates(name, **options)
  new(name, **options).coordinates
end

Instance Method Details

#codeObject

CDEK city code or nil when the city can’t be resolved.



36
37
38
39
# File 'lib/cdek/city_resolver.rb', line 36

def code
  city = cached_city
  city.is_a?(Hash) ? (city["code"] || city[:code]) : nil
end

#coordinatesObject

longitude, latitude

(floats) or nil when coordinates are unknown.

The order matches what the CDEK JS widget expects ([lng, lat]).



43
44
45
46
47
48
49
# File 'lib/cdek/city_resolver.rb', line 43

def coordinates
  city = cached_city
  lng = city_coordinate(city, "longitude")
  lat = city_coordinate(city, "latitude")

  (lng && lat) ? [lng, lat] : nil
end