Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Revised ActiveResource::Base class-level find_by_<attribute>

  • Loading branch information...
commit 5277556bc953acbf1ed1ca1245ca99bb9efbfbd4 1 parent 0147fd3
M. Daniel Dyba dyba authored
10 activeresource/lib/active_resource/base.rb
View
@@ -965,7 +965,15 @@ def split_options(options = {})
def method_missing(method_symbol, *arguments)
case method_symbol.to_s
when /^find_by_([_a-zA-Z]\w*)$/
- Person.find(:first)
+ attribute = $1
+ params = { attribute.to_sym => arguments }
+ if self.schema.key?(attribute)
+ self.find(:all, :params => params)
+ else
+ raise "Couldn't find attribute #{attribute} for #{self}"
+ end
+ else
+ super
end
end
end
6 activeresource/test/abstract_unit.rb
View
@@ -30,7 +30,10 @@ def setup_response
@addy = { :address => { :id => 1, :street => '12345 Street', :country => 'Australia' } }.to_json
@rick = { :person => { :name => "Rick", :age => 25 } }.to_json
@joe = { :person => { :id => 6, :name => 'Joe', :likes_hats => true }}.to_json
- @people = { :people => [ { :person => { :id => 1, :name => 'Matz' } }, { :person => { :id => 2, :name => 'David' } }] }.to_json
+ @people = { :people => [ { :person => { :id => 1, :name => 'Matz' } },
+ { :person => { :id => 2, :name => 'David', :hair_color => "black", :age => 32 } }
+ ]
+ }.to_json
@people_david = { :people => [ { :person => { :id => 2, :name => 'David' } }] }.to_json
@addresses = { :addresses => [{ :address => { :id => 1, :street => '12345 Street', :country => 'Australia' } }] }.to_json
@@ -117,6 +120,7 @@ def setup_response
mock.get "/people/99.json", {}, nil, 404
mock.post "/people.json", {}, @rick, 201, 'Location' => '/people/5.xml'
mock.get "/people.json", {}, @people
+ mock.get "/people.json?name%5B%5D=Matz", {}, @matz
mock.get "/people/1/addresses.json", {}, @addresses
mock.get "/people/1/addresses/1.json", {}, @addy
mock.get "/people/1/addresses/2.xml", {}, nil, 404
9 activeresource/test/cases/finder_test.rb
View
@@ -138,7 +138,12 @@ def test_find_single_by_symbol_from
end
def test_find_by_known_attribute_with_schema_block
- david = Person.find_by_name("David")
- assert_kind_of Person, david
+ matz = Person.find_by_name('Matz')
+ assert_kind_of Person, matz
+ assert_equal "Matz", matz.name
+ end
+
+ def test_find_by_unknown_attribute_with_schema_block
+ assert_raise(RuntimeError) { Person.find_by_birthmonth("December") }
end
end
Please sign in to comment.
Something went wrong with that request. Please try again.