public
Description: Extras for DataMapper, including bridges to DataObjects::Migrations and Merb::DataMapper
Homepage: http://datamapper.org
Clone URL: git://github.com/sam/dm-more.git
dm-more / dm-validations / lib / dm-validations / absent_field_validator.rb
100644 41 lines (30 sloc) 1.014 kb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
module DataMapper
  module Validate
    
    class AbsentFieldValidator < GenericValidator
 
      def initialize(field_name, options={})
        super
        @field_name, @options = field_name, options
      end
      
      def call(target)
        field_value = target.attribute_get(field_name).blank?
        return true if field_value
        
        error_message = @options[:message] || "%s must be absent".t(DataMapper::Inflection.humanize(@field_name))
        add_error(target, error_message , @field_name)
        
        return false
      end
    end
    
    module ValidatesAbsenceOf
      def self.included(base)
        base.extend(ClassMethods)
      end
      
      module ClassMethods
 
        # Validate the absence of a field
        #
        def validates_absence_of(*fields)
          opts = opts_from_validator_args(fields)
          add_validator_to_context(opts, fields, DataMapper::Validate::AbsentFieldValidator)
        end
      end
      
    end
    
  end
end