Module: ValidatesTimeliness::ORM::Mongoid::ClassMethods

Defined in:
lib/validates_timeliness/orm/mongoid.rb

Overview

You need define the fields before you define the validations. It is best to use the plugin parser to avoid errors on a bad field value in Mongoid. Parser will return nil rather than error.

Instance Method Summary collapse

Instance Method Details

#define_timeliness_write_method(attr_name) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/validates_timeliness/orm/mongoid.rb', line 19

def define_timeliness_write_method(attr_name)
  type = timeliness_attribute_type(attr_name)
  method_body, line = <<-EOV, __LINE__ + 1
    def #{attr_name}=(value)
      @timeliness_cache ||= {}
      @timeliness_cache["#{attr_name}"] = value
      #{ "value = Timeliness::Parser.parse(value, :#{type}) if value.is_a?(String)" if ValidatesTimeliness.use_plugin_parser }
      write_attribute(:#{attr_name}, value)
    end
  EOV
  class_eval(method_body, __FILE__, line)
end

#timeliness_attribute_type(attr_name) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/validates_timeliness/orm/mongoid.rb', line 32

def timeliness_attribute_type(attr_name)
  {
    Date => :date,
    Time => :datetime,
    DateTime => :datetime
  }[fields[attr_name.to_s].type] || :datetime
end

#timeliness_validation_for(attr_names, type) ⇒ Object

Mongoid has no bulk attribute method definition hook. It defines them with each field definition. So we likewise define them after each validation is defined.



14
15
16
17
# File 'lib/validates_timeliness/orm/mongoid.rb', line 14

def timeliness_validation_for(attr_names, type)
  super
  attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }
end