Class: ActiveModel::Validations::ShopifyCountryValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/shopify_countries/validators/validates_shopify_country_of.rb

Constant Summary collapse

COUNTRY_ATTRIBUTE =
'code'

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
# File 'lib/shopify_countries/validators/validates_shopify_country_of.rb', line 8

def validate_each(record, attribute, value)
  country_attribute = options[:find_by].presence || COUNTRY_ATTRIBUTE

  raise 'Invalid country attribute' unless %w[name code].include? country_attribute

  country = if country_attribute == 'name'
              ShopifyCountries.find_by_name(value)
            else
              ShopifyCountries.find_by_code(value)
            end

  record.errors.add(attribute, 'country must be in list') if country.nil?
end