Sha256: a25d562a2095610b866caa2f6ef0117098c19c02e99acc3d69213b1ecde07a23

Contents?: true

Size: 1.19 KB

Versions: 10

Compression:

Stored size: 1.19 KB

Contents

require 'active_model'
require 'valvat/syntax'
require 'valvat/lookup'

module ActiveModel
  module Validations
    class ValvatValidator < ::ActiveModel::EachValidator

      def validate_each(record, attribute, value)
        vat = Valvat(value)
        iso_country_code = vat.iso_country_code
        is_valid = true

        if options[:match_country]
          iso_country_code = (record.send(options[:match_country]) || "").upcase
          is_valid = iso_country_code == vat.iso_country_code
        end

        if is_valid
          is_valid = options[:lookup] ? vat.valid? && vat.exists? : vat.valid?

          if is_valid.nil?
            is_valid = options[:lookup] != :fail_if_down
          end
        end

        unless is_valid
          iso_country_code = "eu" if iso_country_code.blank?
          record.errors.add(attribute, :invalid_vat,
            :message => options[:message],
            :country_adjective => I18n.t(
              :"valvat.country_adjectives.#{iso_country_code.downcase}",
              :default => [:"valvat.country_adjectives.eu", "european"]
            )
          )
        end
      end
    end
  end
end

I18n.load_path += Dir["#{File.dirname(__FILE__)}/locales/*.yml"]

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
valvat-0.4.7 lib/valvat/active_model.rb
valvat-0.4.6 lib/valvat/active_model.rb
valvat-0.4.5 lib/valvat/active_model.rb
valvat-0.4.4 lib/valvat/active_model.rb
valvat-0.4.3 lib/valvat/active_model.rb
valvat-0.4.2 lib/valvat/active_model.rb
valvat-0.4.1 lib/valvat/active_model.rb
valvat-0.4.0 lib/valvat/active_model.rb
valvat-0.3.6 lib/valvat/active_model.rb
valvat-0.3.5 lib/valvat/active_model.rb