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

@ -17,11 +17,17 @@ module ValidatesTimeliness
validates_each(attr_names, configuration) do |record, attr_name, value| validates_each(attr_names, configuration) do |record, attr_name, value|
raw_value = record.send("#{attr_name}_before_type_cast") || 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 begin
if raw_value.acts_like?(:time) time = if raw_value.acts_like?(:time)
time = raw_value raw_value
elsif raw_value.is_a?(Date)
raw_value.to_time
else else
time_array = ParseDate.parsedate(raw_value) time_array = ParseDate.parsedate(raw_value)
@ -29,18 +35,30 @@ module ValidatesTimeliness
date = Date.new(*time_array[0..2]) date = Date.new(*time_array[0..2])
# checks if time is valid as it will accept bad date values # checks if time is valid as it will accept bad date values
time = Time.mktime(*time_array) Time.mktime(*time_array)
end end
restriction_methods.each do |option, method| restriction_methods.each do |option, method|
if restriction = options[option] if restriction = configuration[option]
restriction = restriction.to_time compare = case restriction
record.errors.add(attr_name, "must be #{humanize(option)} #{restriction}") unless time.send(method, 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
end end
rescue rescue
record.send(attr_name + "=", nil) record.send("#{attr_name}=", nil)
record.errors.add(attr_name, "is not a valid time") record.errors.add(attr_name, "is not a valid #{column.type}")
next next
end end

View File

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