Class: ActiveRecord::Base

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

Class Method Summary collapse

Class Method Details

.validates_vat_number(*attr_names) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/validates_vat_number.rb', line 34

def self.validates_vat_number(*attr_names)
  configuration = { :on => :save, :allow_blank => false }
  configuration.update(attr_names.extract_options!)
  
  validates_each(attr_names, configuration) do |record, attr_name, value|
    if configuration[:country_method]
      country = record.send(configuration[:country_method]).to_s
      if !ValidatesVatNumber::VAT_PATTERNS.has_key?(country) || value.to_s !~ ValidatesVatNumber::VAT_PATTERNS[country]
        record.errors.add(attr_name, :invalid)
      end
    else
      unless ValidatesVatNumber::VAT_PATTERNS.values.detect { |p| value.to_s =~ p }
        record.errors.add(attr_name, configuration[:message])
      end
    end
  end
end