Hook into undefine_attributes_methods to remove timeliness methods as well

This commit is contained in:
Adam Meehan 2012-02-01 20:38:05 +11:00
parent f8aeeca0a9
commit 5be45b00db
4 changed files with 38 additions and 3 deletions

View File

@ -20,6 +20,11 @@ module ValidatesTimeliness
:datetime
end
def undefine_attribute_methods
super
undefine_timeliness_attribute_methods
end
protected
def define_timeliness_methods(before_type_cast=false)
@ -65,6 +70,12 @@ module ValidatesTimeliness
def generated_timeliness_methods
@generated_timeliness_methods ||= Module.new.tap { |m| include(m) }
end
def undefine_timeliness_attribute_methods
generated_timeliness_methods.module_eval do
instance_methods.each { |m| undef_method(m) }
end
end
end
def _timeliness_raw_value_for(attr_name)

View File

@ -88,8 +88,7 @@ RSpec.configure do |c|
c.include(ModelHelpers)
c.include(ConfigHelper)
c.before do
Person.reset_callbacks(:validate)
PersonWithShim.timeliness_validated_attributes = []
Person._validators.clear
reset_validation_setup_for(Person)
reset_validation_setup_for(PersonWithShim)
end
end

View File

@ -10,6 +10,16 @@ module ConfigHelper
ValidatesTimeliness.send(:"#{preference_name}=", old_value)
end
def reset_validation_setup_for(model_class)
model_class.reset_callbacks(:validate)
model_class._validators.clear
model_class.timeliness_validated_attributes = [] if model_class.respond_to?(:timeliness_validated_attributes)
model_class.undefine_attribute_methods
# This is a hack to avoid a disabled super method error message after an undef
model_class.instance_variable_set(:@generated_attribute_methods, nil)
model_class.instance_variable_set(:@generated_timeliness_methods, nil)
end
module ClassMethods
def with_config(preference_name, temporary_value)
original_config_value = ValidatesTimeliness.send(preference_name)

View File

@ -40,6 +40,21 @@ describe ValidatesTimeliness::AttributeMethods do
e.redefined_birth_date_called.should be_true
end
it 'should be undefined if model class has dynamic attribute methods reset' do
# Force method definitions
PersonWithShim.validates_date :birth_date
r = PersonWithShim.new
r.birth_date = Time.now
write_method = RUBY_VERSION < '1.9' ? 'birth_date=' : :birth_date=
PersonWithShim.send(:generated_timeliness_methods).instance_methods.should include(write_method)
PersonWithShim.undefine_attribute_methods
PersonWithShim.send(:generated_timeliness_methods).instance_methods.should_not include(write_method)
end
context "with plugin parser" do
with_config(:use_plugin_parser, true)