refactor #read_ and #write_attribute to behave the same when called with a missing property

This commit is contained in:
Will Leinweber 2010-08-11 22:27:53 -05:00
parent aac6b80d26
commit 1a7154f5bf
2 changed files with 90 additions and 71 deletions

View file

@ -23,12 +23,12 @@ module CouchRest
end
def read_attribute(property)
self[property.to_s]
prop = find_property!(property)
self[prop.to_s]
end
def write_attribute(property, value)
prop = property.is_a?(Property) ? property : self.class.properties.detect {|p| p.to_s == property.to_s}
raise "Missing property definition for #{property.to_s}" unless prop
prop = find_property!(property)
self[prop.to_s] = prop.cast(self, value)
end
@ -40,6 +40,13 @@ module CouchRest
end
end
private
def find_property!(property)
prop = property.is_a?(Property) ? property : self.class.properties.detect {|p| p.to_s == property.to_s}
raise ArgumentError, "Missing property definition for #{property.to_s}" unless prop
prop
end
module ClassMethods
def property(name, *options, &block)

View file

@ -59,6 +59,7 @@ describe "Model properties" do
@card.updated_at.should_not be_nil
end
describe '#read_attribute' do
it "should let you use read_attribute method" do
@card.last_name = "Aimonetti"
@card.read_attribute(:last_name).should eql('Aimonetti')
@ -67,6 +68,12 @@ describe "Model properties" do
@card.read_attribute(last_name_prop).should eql('Aimonetti')
end
it 'should raise an error if the property does not exist' do
expect { @card.read_attribute(:this_property_should_not_exist) }.to raise_error(ArgumentError)
end
end
describe '#write_attribute' do
it "should let you use write_attribute method" do
@card.write_attribute(:last_name, 'Aimonetti 1')
@card.last_name.should eql('Aimonetti 1')
@ -77,6 +84,10 @@ describe "Model properties" do
@card.last_name.should eql('Aimonetti 3')
end
it 'should raise an error if the property does not exist' do
expect { @card.write_attribute(:this_property_should_not_exist, 823) }.to raise_error(ArgumentError)
end
it "should let you use write_attribute on readonly properties" do
lambda {
@card.read_only_value = "foo"
@ -96,6 +107,7 @@ describe "Model properties" do
@card.first_name.class.should eql(Hash)
@card.first_name[:name].should eql("Sam")
end
end
describe "mass assignment protection" do