2024-04-29 00:17:15 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-02-13 18:18:20 +01:00
|
|
|
class Champs::PaysChamp < Champs::TextChamp
|
2024-03-30 08:02:30 +01:00
|
|
|
with_options if: :validate_champ_value? do
|
|
|
|
validates :external_id, inclusion: APIGeoService.countries.pluck(:code), allow_nil: true, allow_blank: false
|
|
|
|
validates :value, inclusion: APIGeoService.countries.pluck(:name), allow_nil: true, allow_blank: false
|
|
|
|
end
|
|
|
|
|
|
|
|
# def value=(code) can reset champs to nil if value is empty, in case of prefill
|
|
|
|
# we do not want to try to save the champ with an nil value
|
|
|
|
with_options if: -> { validation_context == :prefill } do
|
|
|
|
validates :external_id, inclusion: APIGeoService.countries.pluck(:code), allow_nil: false, allow_blank: false
|
|
|
|
validates :value, inclusion: APIGeoService.countries.pluck(:name), allow_nil: false, allow_blank: false
|
|
|
|
end
|
2023-01-18 12:52:38 +01:00
|
|
|
|
2022-12-20 21:28:42 +01:00
|
|
|
def selected
|
|
|
|
code || value
|
|
|
|
end
|
|
|
|
|
|
|
|
def value=(code)
|
|
|
|
if code&.size == 2
|
|
|
|
self.external_id = code
|
|
|
|
super(APIGeoService.country_name(code, locale: 'FR'))
|
|
|
|
elsif code.blank?
|
|
|
|
self.external_id = nil
|
|
|
|
super(nil)
|
|
|
|
elsif code != value
|
2024-03-30 08:02:30 +01:00
|
|
|
self.external_id = APIGeoService.country_code(code) # lookup by code which is a country name
|
|
|
|
|
|
|
|
if self.external_id # if we match a country code, lookup for country name with code
|
|
|
|
super(APIGeoService.country_name(self.external_id, locale: 'FR'))
|
|
|
|
else # if we did not match any country code, external_id is nil as well as value
|
|
|
|
super(nil)
|
|
|
|
end
|
2021-08-31 12:49:35 +02:00
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2022-12-20 21:28:42 +01:00
|
|
|
def code
|
|
|
|
external_id || APIGeoService.country_code(value)
|
2021-08-31 12:49:35 +02:00
|
|
|
end
|
|
|
|
|
2022-12-21 17:35:05 +01:00
|
|
|
def name
|
2022-12-27 16:28:34 +01:00
|
|
|
if external_id.present?
|
2022-12-20 21:28:42 +01:00
|
|
|
APIGeoService.country_name(external_id)
|
|
|
|
else
|
|
|
|
value.present? ? value.to_s : ''
|
|
|
|
end
|
2021-08-31 12:49:35 +02:00
|
|
|
end
|
2018-02-13 18:18:20 +01:00
|
|
|
end
|