simplify format arguments in parser

This commit is contained in:
Adam Meehan 2010-10-01 09:07:59 +10:00
parent f2f1e0b165
commit 8a0b2418bb

View File

@ -151,17 +151,17 @@ module ValidatesTimeliness
# The code can be used to manipulate the arg value if required, otherwise # The code can be used to manipulate the arg value if required, otherwise
# should just be the arg name. # should just be the arg name.
# #
cattr_accessor :format_proc_args cattr_accessor :format_components
@@format_proc_args = { @@format_components = {
:year => [0, 'y', 'unambiguous_year(y)'], :year => [ 0, 'unambiguous_year(year)'],
:month => [1, 'm', 'month_index(m)'], :month => [ 1, 'month_index(month)'],
:day => [2, 'd', 'd'], :day => [ 2 ],
:hour => [3, 'h', 'full_hour(h, md ||= nil)'], :hour => [ 3, 'full_hour(hour, meridian ||= nil)'],
:min => [4, 'n', 'n'], :min => [ 4 ],
:sec => [5, 's', 's'], :sec => [ 5 ],
:usec => [6, 'u', 'microseconds(u)'], :usec => [ 6, 'microseconds(usec)'],
:offset => [7, 'z', 'offset_in_seconds(z)'], :offset => [ 7, 'offset_in_seconds(offset)'],
:meridian => [nil, 'md', nil] :meridian => [ nil ]
} }
@@type_wrapper = { @@type_wrapper = {
@ -350,20 +350,18 @@ module ValidatesTimeliness
end end
# Compiles a format method which maps the regexp capture groups to method # Compiles a format method which maps the regexp capture groups to method
# arguments based on order captured. A time array is built using the values # arguments based on order captured. A time array is built using the argument
# in the position indicated by the first element of the proc arg array. # values placed in the position defined by format component.
# #
def compile_format_method(order, name) def compile_format_method(components, name)
values = [nil] * 7 values = [nil] * 7
args = [] components.each do |component|
order.each do |part| position, code = *format_components[component]
proc_arg = format_proc_args[part] values[position] = code || component if position
args << proc_arg[1]
values[proc_arg[0]] = proc_arg[2] if proc_arg[0]
end end
class_eval <<-DEF class_eval <<-DEF
class << self class << self
define_method(:"format_#{name}") do |#{args.join(',')}| define_method(:"format_#{name}") do |#{components.join(',')}|
[#{values.map {|i| i || 'nil' }.join(',')}].map {|i| i.is_a?(Float) ? i : i.to_i } [#{values.map {|i| i || 'nil' }.join(',')}].map {|i| i.is_a?(Float) ? i : i.to_i }
end end
end end