refactored restrictions in method

This commit is contained in:
Adam Meehan 2008-07-07 15:19:32 +10:00
parent bb0e64857a
commit 3f286b9aee

View File

@ -22,19 +22,22 @@ module ValidatesTimeliness
# Override this method to use any date parsing algorithm you like such as # Override this method to use any date parsing algorithm you like such as
# Chronic. Just return nil for an invalid value and a Time object for a # Chronic. Just return nil for an invalid value and a Time object for a
# valid parsed value. # valid parsed value.
#
# Remember, if the date portion is pre the Unix epoch the return object
# will need to be a datatime. But luckily Rails, since version 2, will
# automatically handle the fall back to a DateTime when you create a time
# with Time.new or #to_time.
def timeliness_date_time_parse(raw_value) def timeliness_date_time_parse(raw_value)
begin time_array = ParseDate.parsedate(raw_value, true)
time_array = ParseDate.parsedate(raw_value)
# checks if date part is valid, enforcing days in a month unlike Time # checks if date part is valid, enforcing days in a month unlike Time
Date.new(*time_array[0..2]) Date.new(*time_array[0..2])
# checks if time part is valid and returns object # checks if time part is valid and returns object
Time.mktime(*time_array) Time.mktime(*time_array)
rescue rescue
nil nil
end
end end
def validates_timeliness_of(*attr_names) def validates_timeliness_of(*attr_names)
@ -105,28 +108,25 @@ module ValidatesTimeliness
time = value.send(conversion_method) time = value.send(conversion_method)
restriction_methods.each do |option, method| restriction_methods.each do |option, method|
if restriction = configuration[option] next unless restriction = configuration[option]
begin begin
compare = case restriction compare = case restriction
when Date when Time, Date, DateTime
restriction restriction
when Time, DateTime when Symbol
restriction.respond_to?(:in_time_zone) ? restriction.in_time_zone : restriction record.send(restriction)
when Symbol when Proc
record.send(restriction) restriction.call(record)
when Proc else
restriction.call(record) timeliness_date_time_parse(restriction)
else end
timeliness_date_time_parse(restriction)
end next if compare.nil?
next if compare.nil? compare = compare.send(conversion_method)
compare = compare.send(conversion_method) if compare record.errors.add(attr_name, configuration["#{option}_message".to_sym] % compare) unless time.send(method, compare)
rescue
record.errors.add(attr_name, configuration["#{option}_message".to_sym] % compare) unless time.send(method, compare) record.errors.add(attr_name, "restriction '#{option}' value was invalid")
rescue
record.errors.add(attr_name, "restriction '#{option}' value was invalid")
end
end end
end end
end end