Permalink
Browse files

Better timeliness_type_cast_code

  • Loading branch information...
1 parent ea7c9ec commit ac989784415231a906af89a3f79543eb462f9c4b @adzap adzap committed May 8, 2011
View
8 lib/validates_timeliness/attribute_methods.rb
@@ -35,7 +35,8 @@ def define_timeliness_write_method(attr_name)
def #{attr_name}=(value)
@timeliness_cache ||= {}
@timeliness_cache["#{attr_name}"] = value
- #{ timeliness_type_cast_code(attr_name) if ValidatesTimeliness.use_plugin_parser }
+
+ #{ "if value.is_a?(String)\n#{timeliness_type_cast_code(attr_name, 'value')}\nend" if ValidatesTimeliness.use_plugin_parser }
super
end
EOV
@@ -51,11 +52,12 @@ def #{attr_name}_before_type_cast
generated_timeliness_methods.module_eval(method_body, __FILE__, line)
end
- def timeliness_type_cast_code(attr_name)
+ def timeliness_type_cast_code(attr_name, var_name)
type = timeliness_attribute_type(attr_name)
timezone_aware = timeliness_attribute_timezone_aware?(attr_name)
+ timezone = :current if timezone_aware
- "value = Timeliness::Parser.parse(value, :#{type}, :zone => (:current if #{timezone_aware})) if value.is_a?(String)"
+ "#{var_name} = Timeliness::Parser.parse(#{var_name}, :#{type}, :zone => #{timezone.inspect})"
end
def generated_timeliness_methods
View
9 lib/validates_timeliness/orm/active_record.rb
@@ -19,15 +19,12 @@ def timeliness_attribute_type(attr_name)
columns_hash[attr_name.to_s].type
end
- def timeliness_type_cast_code(attr_name)
+ def timeliness_type_cast_code(attr_name, var_name)
type = timeliness_attribute_type(attr_name)
- timezone_aware = timeliness_attribute_timezone_aware?(attr_name)
<<-END
- if value.is_a?(String)
- value = Timeliness::Parser.parse(value, :#{type}, :zone => (:current if #{timezone_aware}))
- value = value.to_date if value && :#{type} == :date
- end
+ #{super}
+ #{var_name} = #{var_name}.to_date if #{var_name} && :#{type} == :date
END
end
end
View
13 lib/validates_timeliness/orm/mongoid.rb
@@ -16,17 +16,10 @@ def timeliness_validation_for(attr_names, type)
attr_names.each { |attr_name| define_timeliness_write_method(attr_name) }
end
- def define_timeliness_write_method(attr_name)
+ def timeliness_type_cast_code(attr_name, var_name)
type = timeliness_attribute_type(attr_name)
- method_body, line = <<-EOV, __LINE__ + 1
- def #{attr_name}=(value)
- @timeliness_cache ||= {}
- @timeliness_cache["#{attr_name}"] = value
- #{ "value = Timeliness::Parser.parse(value, :#{type}) if value.is_a?(String)" if ValidatesTimeliness.use_plugin_parser }
- write_attribute(:#{attr_name}, value)
- end
- EOV
- class_eval(method_body, __FILE__, line)
+
+ "#{var_name} = Timeliness::Parser.parse(value, :#{type})"
end
def timeliness_attribute_type(attr_name)

0 comments on commit ac98978

Please sign in to comment.