salesking / sepa_king

Ruby gem for creating SEPA XML files
MIT License
150 stars 117 forks source link

Validate the application models #21

Closed schorsch closed 10 years ago

schorsch commented 10 years ago

so one can use them in their own models for field validation

ledermann commented 10 years ago

I like the idea, but IMHO the code can be improved: A Validator allows the attribute name to be dynamic. validates_withcan take an option hash.

Example:

class IBANValidator < ActiveModel::Validator
  def validate(record)
    field_name = options[:field_name] || :iban
    value = record.send(field_name)

    unless IBANTools::IBAN.valid?(value.to_s)
      record.errors.add(field_name, :invalid)
    end
  end
end

...

class User
  # Validate the attribute "iban_the_terrible" as IBAN
  validates_with SEPA::IBANValidator, :field_name => :iban_the_terrible
end
ledermann commented 10 years ago

Added some changes. IMHO this handles better custom names in the database schema