diff --git a/init.rb b/init.rb index 8bee271..da111ed 100644 --- a/init.rb +++ b/init.rb @@ -1,3 +1,3 @@ -raise "Rails version must be 2.0 or greater to use validates_timeliness plugin" if Rails::VERSION::MAJOR < 2 +raise "Rails version must be 2.0 or greater to use validates_timeliness plugin" if Rails::VERSION::MAJOR < 2 require 'validates_timeliness' diff --git a/lib/validates_timeliness/validations.rb b/lib/validates_timeliness/validations.rb index 6e8d892..60b2bfc 100644 --- a/lib/validates_timeliness/validations.rb +++ b/lib/validates_timeliness/validations.rb @@ -17,11 +17,17 @@ module ValidatesTimeliness validates_each(attr_names, configuration) do |record, attr_name, value| raw_value = record.send("#{attr_name}_before_type_cast") || value - next if raw_value.is_nil? and options[:allow_nil] + if raw_value.nil? + record.errors.add(attr_name, "cant' be blank") unless configuration[:allow_nil] + next + end + column = record.column_for_attribute(attr_name) begin - if raw_value.acts_like?(:time) - time = raw_value + time = if raw_value.acts_like?(:time) + raw_value + elsif raw_value.is_a?(Date) + raw_value.to_time else time_array = ParseDate.parsedate(raw_value) @@ -29,18 +35,30 @@ module ValidatesTimeliness date = Date.new(*time_array[0..2]) # checks if time is valid as it will accept bad date values - time = Time.mktime(*time_array) + Time.mktime(*time_array) end restriction_methods.each do |option, method| - if restriction = options[option] - restriction = restriction.to_time - record.errors.add(attr_name, "must be #{humanize(option)} #{restriction}") unless time.send(method, restriction) + if restriction = configuration[option] + compare = case restriction + when Time, Date, DateTime + restriction.to_time + when Symbol + record.send(restriction).to_time + when Proc + restriction.call(record) + end + + begin + record.errors.add(attr_name, "must be #{option.to_s.humanize.downcase} #{compare}") unless time.send(method, compare) + rescue + record.errors.add(attr_name, "restriction '#{option}' value was invalid") + end end end rescue - record.send(attr_name + "=", nil) - record.errors.add(attr_name, "is not a valid time") + record.send("#{attr_name}=", nil) + record.errors.add(attr_name, "is not a valid #{column.type}") next end diff --git a/spec/resources/person.rb b/spec/resources/person.rb index c2e188d..16426dc 100644 --- a/spec/resources/person.rb +++ b/spec/resources/person.rb @@ -1,3 +1,3 @@ class Person < ActiveRecord::Base - + set_table_name 'people' end