added specs for validation

This commit is contained in:
Adam Meehan 2008-05-03 15:52:40 +10:00
parent 8751eddac6
commit cae3d8cb84
3 changed files with 29 additions and 11 deletions

View File

@ -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'

View File

@ -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

View File

@ -1,3 +1,3 @@
class Person < ActiveRecord::Base
set_table_name 'people'
end