Module: DataMapper::Validate::ValidatesWithMethod

Included in:
ClassMethods
Defined in:
lib/gems/dm-validations-0.9.9/lib/dm-validations/method_validator.rb

Overview

class MethodValidator

Instance Method Summary collapse

Instance Method Details

#validates_with_method(*fields) ⇒ Object

Validate using the given method. The method given needs to return:

result::<Boolean>, Error Message::<String>

Examples:

Usage
require 'dm-validations'

class Page
  include DataMapper::Resource

  property :zip_code, String

  validates_with_method :in_the_right_location?

  def in_the_right_location?
    if @zip_code == "94301"
      return true
    else
      return [false, "You're in the wrong zip code"]
    end
  end

  # A call to valid? will return false and
  # populate the object's errors with "You're in the
  # wrong zip code" unless zip_code == "94301"

  # You can also specify field:

  validates_with_method :zip_code, :in_the_right_location?

  # it will add returned error message to :zip_code field


61
62
63
64
# File 'lib/gems/dm-validations-0.9.9/lib/dm-validations/method_validator.rb', line 61

def validates_with_method(*fields)
  opts = opts_from_validator_args(fields)
  add_validator_to_context(opts, fields, DataMapper::Validate::MethodValidator)
end