lib/sequel/plugins/validation_helpers.rb in sequel-3.7.0 vs lib/sequel/plugins/validation_helpers.rb in sequel-3.8.0
- old
+ new
@@ -52,10 +52,11 @@
:length_range=>{:message=>lambda{|range| "is too short or too long"}},
:max_length=>{:message=>lambda{|max| "is longer than #{max} characters"}},
:min_length=>{:message=>lambda{|min| "is shorter than #{min} characters"}},
:not_string=>{:message=>lambda{|type| type ? "is not a valid #{type}" : "is a string"}},
:numeric=>{:message=>lambda{"is not a number"}},
+ :type=>{:message=>lambda{|klass| "is not a #{klass}"}},
:presence=>{:message=>lambda{"is not present"}},
:unique=>{:message=>lambda{'is already taken'}}
}
module InstanceMethods
@@ -108,20 +109,26 @@
# be a string in an invalid format, and if typecasting succeeds, the value will
# not be a string.
def validates_not_string(atts, opts={})
validatable_attributes_for_type(:not_string, atts, opts){|a,v,m| validation_error_message(m, (db_schema[a]||{})[:type]) if v.is_a?(String)}
end
-
+
# Check attribute value(s) string representation is a valid float.
def validates_numeric(atts, opts={})
validatable_attributes_for_type(:numeric, atts, opts) do |a,v,m|
begin
Kernel.Float(v.to_s)
nil
rescue
validation_error_message(m)
end
end
+ end
+
+ # Check if value is an instance of a class
+ def validates_type(klass, atts, opts={})
+ klass = klass.to_s.constantize if klass.is_a?(String) || klass.is_a?(Symbol)
+ validatable_attributes_for_type(:type, atts, opts){|a,v,m| validation_error_message(m, klass) if v && !v.is_a?(klass)}
end
# Check attribute value(s) is not considered blank by the database, but allow false values.
def validates_presence(atts, opts={})
validatable_attributes_for_type(:presence, atts, opts){|a,v,m| validation_error_message(m) if model.db.send(:blank_object?, v) && v != false}