diff --git a/lib/phony_rails.rb b/lib/phony_rails.rb index e897438..1341ea1 100644 --- a/lib/phony_rails.rb +++ b/lib/phony_rails.rb @@ -49,6 +49,7 @@ def set_phony_normalized_numbers(attributes, options = {}) options[:country_code] ||= self.country_code if self.respond_to?(:country_code) attributes.each do |attribute| attribute_name = options[:as] || attribute + raise RuntimeError, "No attribute #{attribute_name} found on #{self.class.name} (PhonyRails)" if not self.respond_to?(attribute_name) write_attribute(attribute_name, PhonyRails.normalize_number(read_attribute(attribute), options)) end end @@ -69,12 +70,9 @@ def phony_normalize(*attributes) raise ArgumentError, ':as option can not be used on phony_normalize with multiple attribute names! (PhonyRails)' if attributes.size > 1 raise ArgumentError, "'#{options[:as]}' is not an attribute on #{self.name}. You might want to use 'phony_normalized_method :#{attributes.first}' (PhonyRails)" if not self.attribute_method?(options[:as]) end - attributes.each do |attribute| - raise ArgumentError, "No attribute #{attribute} found on #{self.name} (PhonyRails)" if not self.attribute_method?(attribute) - # Add before validation that saves a normalized version of the phone number - self.before_validation do - set_phony_normalized_numbers(attributes, options) - end + # Add before validation that saves a normalized version of the phone number + self.before_validation do + set_phony_normalized_numbers(attributes, options) end end diff --git a/spec/lib/phony_rails_spec.rb b/spec/lib/phony_rails_spec.rb index da08e6b..bfb50e9 100644 --- a/spec/lib/phony_rails_spec.rb +++ b/spec/lib/phony_rails_spec.rb @@ -14,7 +14,7 @@ s.phony_formatted!(:normalize => :NL, :format => :international).should eql('+31 10 1234123') s.should eql("+31 10 1234123") end - + end describe 'with normalize option' do @@ -143,6 +143,12 @@ Home.phony_normalize(:phone_number, :as => 'phone_number_as_normalized') }.should_not raise_error(ArgumentError) end + + it "should accept a non existing attribute name" do + lambda { + Dummy.phony_normalize(:non_existing_attribute) + }.should_not raise_error + end end describe 'using ActiveRecord#phony_normalized_method' do @@ -219,5 +225,14 @@ home.valid?.should be_true home.phone_number_as_normalized.should eql('31101234123') end + + it "should raise a RuntimeError at validation if the attribute doesn't exist" do + Dummy.phony_normalize :non_existing_attribute + + dummy = Dummy.new + lambda { + dummy.valid? + }.should raise_error(RuntimeError) + end end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index b633e3e..24ffc91 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -26,6 +26,9 @@ class Home < ActiveRecord::Base phony_normalize :phone_number # normalized on validation end +class Dummy < Home +end + RSpec.configure do |config| - # some (optional) config here + # some (optional) config here end \ No newline at end of file