Refactor AR shim for v3.1 checks

This commit is contained in:
Adam Meehan 2012-02-01 21:24:38 +11:00
parent 5be45b00db
commit 84316bc73a
2 changed files with 29 additions and 23 deletions

View File

@ -41,7 +41,6 @@ module ValidatesTimeliness
original_value = value
@timeliness_cache ||= {}
@timeliness_cache["#{attr_name}"] = original_value
#{ "if value.is_a?(String)\n#{timeliness_type_cast_code(attr_name, 'value')}\nend" if ValidatesTimeliness.use_plugin_parser }
super(value)

View File

@ -8,7 +8,9 @@ module ValidatesTimeliness
end
included do
unless ValidatesTimeliness::ORM::ActiveRecord.use_plugin_cache?
if ValidatesTimeliness::ORM::ActiveRecord.use_plugin_cache?
include Reload
else
# Just use the built-in before_type_cast retrieval
alias_method :_timeliness_raw_value_for, :read_attribute_before_type_cast
end
@ -18,25 +20,32 @@ module ValidatesTimeliness
def define_attribute_methods
super
use_before_type_cast = ValidatesTimeliness::ORM::ActiveRecord.use_plugin_cache?
define_timeliness_methods use_before_type_cast
end
if use_before_type_cast || ValidatesTimeliness.use_plugin_parser
define_timeliness_methods(use_before_type_cast)
def define_timeliness_methods(before_type_cast=false)
return if timeliness_validated_attributes.blank?
timeliness_validated_attributes.each do |attr_name|
if before_type_cast
define_timeliness_write_method(attr_name)
define_timeliness_before_type_cast_method(attr_name)
elsif ValidatesTimeliness.use_plugin_parser
define_timeliness_write_method_without_cache(attr_name)
end
end
end
# ActiveRecord >= 3.1.x has correct before_type_cast implementation to support plugin, except parser
unless ValidatesTimeliness::ORM::ActiveRecord.use_plugin_cache?
def define_timeliness_write_method(attr_name)
method_body, line = <<-EOV, __LINE__ + 1
def #{attr_name}=(value)
original_value = value
if original_value.is_a?(String)\n#{timeliness_type_cast_code(attr_name, 'value')}\nend
super(value)
@attributes['#{attr_name}'] = original_value
end
EOV
generated_timeliness_methods.module_eval(method_body, __FILE__, line)
end
def define_timeliness_write_method_without_cache(attr_name)
method_body, line = <<-EOV, __LINE__ + 1
def #{attr_name}=(value)
original_value = value
if value.is_a?(String)\n#{timeliness_type_cast_code(attr_name, 'value')}\nend
super(value)
@attributes['#{attr_name}'] = original_value
end
EOV
generated_timeliness_methods.module_eval(method_body, __FILE__, line)
end
def timeliness_attribute_timezone_aware?(attr_name)
@ -51,15 +60,13 @@ module ValidatesTimeliness
def timeliness_type_cast_code(attr_name, var_name)
type = timeliness_attribute_type(attr_name)
<<-END
#{super}
#{var_name} = #{var_name}.to_date if #{var_name} && :#{type} == :date
END
method_body = super
method_body << "\n#{var_name} = #{var_name}.to_date if #{var_name}" if type == :date
method_body
end
end
# ActiveRecord >= 3.1.x needs no cached cleared
if use_plugin_cache?
module Reload
def reload(*args)
_clear_timeliness_cache
super