| Module | SmartleafValidations |
| In: |
lib/smartleaf_validations.rb
|
Module to add extra general-purpose validations — Particularly validates_in_range
validates_in_range :foo, :min => bar, :max => baz, :allow_nil => true/false
Validates presence and numericality of foo, and also that its value is between the stated limits (inclusive). Either :min or :max may be omitted, in which case the corresponding side of the range is not checked.
:allow_nil defaults to false if not specified. If true, nils are allowed, in addition to numeric values in the range.
# File lib/smartleaf_validations.rb, line 37
37: def validates_in_range attr, opts = {}
38:
39: min, max = opts[:min], opts[:max]
40:
41: if min.nil? then
42: opts[:message] ||= "should be at most #{max}"
43: elsif max.nil? then
44: opts[:message] ||= "should be at least #{min}"
45: else
46: opts[:message] ||= "should be between #{min} and #{max}"
47: end
48:
49: validates_each attr, opts do |rec, attr, val|
50: begin
51: return if opts[:allow_nil] && val.nil?
52: val = Kernel.Float( rec.send( "#{attr}_before_type_cast" ))
53: if ((!min.nil? && val < min) || (!max.nil? && val > max)) then
54: rec.errors.add attr, opts[:message]
55: end
56: rescue ArgumentError, TypeError
57: rec.errors.add attr, opts[:message]
58: end
59: end
60: end
validates_not_in_future :date_field, :allow_nil => true/false
Validates that the date_field is set to a valid date which is not in the future. :allow_nil may be specified, and defaults false.
# File lib/smartleaf_validations.rb, line 67
67: def validates_not_in_future attr, opts = {}
68: validates_each attr, opts do |rec, attr, val|
69: begin
70: if val.nil?
71: if !opts[:allow_nil]
72: rec.errors.add attr, "must be given"
73: end
74: elsif val.to_date > Date.today
75: rec.errors.add attr, "must not be in the future"
76: end
77: rescue NoMethodError, TypeError
78: rec.errors.add attr, "must be a date"
79: end
80: end
81: end