Class: CountriesDB::Rails::CountriesdbValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- CountriesDB::Rails::CountriesdbValidator
- Defined in:
- lib/countriesdb/rails/validators.rb
Overview
ActiveModel validator for country codes
Instance Method Summary collapse
Instance Method Details
#validate_each(record, attribute, value) ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/countriesdb/rails/validators.rb', line 8 def validate_each(record, attribute, value) api_key = Rails.application.config.countriesdb&.dig(:api_key) || ENV['COUNTRIESDB_API_KEY'] backend_url = Rails.application.config.countriesdb&.dig(:backend_url) || ENV['COUNTRIESDB_BACKEND_URL'] || 'https://api.countriesdb.com' return if api_key.nil? || api_key.empty? validator = CountriesDB::Validator.new(api_key: api_key, backend_url: backend_url) # Determine validation type if [:subdivision] country_attr = [:country] || :country country = record.send(country_attr) result = validator.validate_subdivision( value, country, follow_related: [:follow_related] || false, allow_parent_selection: [:allow_parent_selection] || false ) else result = validator.validate_country( value, follow_upward: [:follow_upward] || false ) end unless result[:valid] record.errors.add(attribute, result[:message] || 'is invalid') end end |