@author teamon @since 0.9
Validate using the given block. The block given needs to return:
@example [Usage]
require 'dm-validations' class Page include DataMapper::Resource property :zip_code, String validates_with_block do if @zip_code == "94301" true else [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_block :zip_code do if @zip_code == "94301" true else [false, "You're in the wrong zip code"] end end # it will add returned error message to :zip_code field
# File lib/dm-validations/validators/block_validator.rb, line 41 41: def validates_with_block(*fields, &block) 42: @__validates_with_block_count ||= 0 43: @__validates_with_block_count += 1 44: 45: # create method and pass it to MethodValidator 46: unless block_given? 47: raise ArgumentError, 'You need to pass a block to validates_with_block method' 48: end 49: 50: method_name = "__validates_with_block_#{@__validates_with_block_count}".to_sym 51: define_method(method_name, &block) 52: 53: options = fields.last.is_a?(Hash) ? fields.last.pop.dup : {} 54: options[:method] = method_name 55: fields = [method_name] if fields.empty? 56: 57: validators.add(MethodValidator, *fields + [options]) 58: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.