diff options
Diffstat (limited to 'activeresource')
-rw-r--r-- | activeresource/CHANGELOG | 324 | ||||
-rw-r--r-- | activeresource/CHANGELOG.md | 334 | ||||
-rw-r--r-- | activeresource/README.rdoc | 10 | ||||
-rw-r--r-- | activeresource/activeresource.gemspec | 2 | ||||
-rw-r--r-- | activeresource/lib/active_resource/base.rb | 28 | ||||
-rw-r--r-- | activeresource/lib/active_resource/connection.rb | 7 | ||||
-rw-r--r-- | activeresource/lib/active_resource/custom_methods.rb | 50 | ||||
-rw-r--r-- | activeresource/lib/active_resource/exceptions.rb | 32 | ||||
-rw-r--r-- | activeresource/test/cases/authorization_test.rb | 6 | ||||
-rw-r--r-- | activeresource/test/cases/base/load_test.rb | 19 | ||||
-rw-r--r-- | activeresource/test/cases/base_test.rb | 44 | ||||
-rw-r--r-- | activeresource/test/cases/connection_test.rb | 19 |
12 files changed, 496 insertions, 379 deletions
diff --git a/activeresource/CHANGELOG b/activeresource/CHANGELOG deleted file mode 100644 index 25f9242b98..0000000000 --- a/activeresource/CHANGELOG +++ /dev/null @@ -1,324 +0,0 @@ -*Rails 3.1.0 (unreleased)* - -* The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set `self.format = :xml` in the class. eg. - -class User < ActiveResource::Base - self.format = :xml -end - - -*Rails 3.0.7 (April 18, 2011)* - -* No changes. - - -*Rails 3.0.6 (April 5, 2011) - -* No changes. - - -*Rails 3.0.5 (February 26, 2011)* - -* No changes. - - -*Rails 3.0.4 (February 8, 2011)* - -* No changes. - - -*Rails 3.0.3 (November 16, 2010)* - -* No changes. - - -*Rails 3.0.2 (November 15, 2010)* - -* No changes - - -*Rails 3.0.1 (October 15, 2010)* - -* No Changes, just a version bump. - - -*Rails 3.0.0 (August 29, 2010)* - -* JSON: set Base.include_root_in_json = true to include a root value in the JSON: {"post": {"title": ...}}. Mirrors the Active Record option. [Santiago Pastorino] - -* Add support for errors in JSON format. #1956 [Fabien Jakimowicz] - -* Recognizes 410 as Resource Gone. #2316 [Jordan Brough, Jatinder Singh] - -* More thorough SSL support. #2370 [Roy Nicholson] - -* HTTP proxy support. #2133 [Marshall Huss, Sébastien Dabet] - - -*2.3.2 [Final] (March 15, 2009)* - -* Nothing new, just included in 2.3.2 - - -*2.2.1 [RC2] (November 14th, 2008)* - -* Fixed that ActiveResource#post would post an empty string when it shouldn't be posting anything #525 [Paolo Angelini] - - -*2.2.0 [RC1] (October 24th, 2008)* - -* Add ActiveResource::Base#to_xml and ActiveResource::Base#to_json. #1011 [Rasik Pandey, Cody Fauser] - -* Add ActiveResource::Base.find(:last). [#754 state:resolved] (Adrian Mugnolo) - -* Fixed problems with the logger used if the logging string included %'s [#840 state:resolved] (Jamis Buck) - -* Fixed Base#exists? to check status code as integer [#299 state:resolved] (Wes Oldenbeuving) - - -*2.1.0 (May 31st, 2008)* - -* Fixed response logging to use length instead of the entire thing (seangeo) [#27] - -* Fixed that to_param should be used and honored instead of hardcoding the id #11406 [gspiers] - -* Improve documentation. [Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert] - -* Use HEAD instead of GET in exists? [bscofield] - -* Fix small documentation typo. Closes #10670 [Luca Guidi] - -* find_or_create_resource_for handles module nesting. #10646 [xavier] - -* Allow setting ActiveResource::Base#format before #site. [Rick Olson] - -* Support agnostic formats when calling custom methods. Closes #10635 [joerichsen] - -* Document custom methods. #10589 [Cheah Chu Yeow] - -* Ruby 1.9 compatibility. [Jeremy Kemper] - - -*2.0.2 (December 16th, 2007)* - -* Added more specific exceptions for 400, 401, and 403 (all descending from ClientError so existing rescues will work) #10326 [trek] - -* Correct empty response handling. #10445 [seangeo] - - -*2.0.1 (December 7th, 2007)* - -* Don't cache net/http object so that ActiveResource is more thread-safe. Closes #10142 [kou] - -* Update XML documentation examples to include explicit type attributes. Closes #9754 [Josh Susser] - -* Added one-off declarations of mock behavior [David Heinemeier Hansson]. Example: - - Before: - ActiveResource::HttpMock.respond_to do |mock| - mock.get "/people/1.xml", {}, "<person><name>David</name></person>" - end - - Now: - ActiveResource::HttpMock.respond_to.get "/people/1.xml", {}, "<person><name>David</name></person>" - -* Added ActiveResource.format= which defaults to :xml but can also be set to :json [David Heinemeier Hansson]. Example: - - class Person < ActiveResource::Base - self.site = "http://app/" - self.format = :json - end - - person = Person.find(1) # => GET http://app/people/1.json - person.name = "David" - person.save # => PUT http://app/people/1.json {name: "David"} - - Person.format = :xml - person.name = "Mary" - person.save # => PUT http://app/people/1.json <person><name>Mary</name></person> - -* Fix reload error when path prefix is used. #8727 [Ian Warshak] - -* Remove ActiveResource::Struct because it hasn't proven very useful. Creating a new ActiveResource::Base subclass is often less code and always clearer. #8612 [Josh Peek] - -* Fix query methods on resources. [Cody Fauser] - -* pass the prefix_options to the instantiated record when using find without a specific id. Closes #8544 [Eloy Duran] - -* Recognize and raise an exception on 405 Method Not Allowed responses. #7692 [Josh Peek] - -* Handle string and symbol param keys when splitting params into prefix params and query params. - - Comment.find(:all, :params => { :article_id => 5, :page => 2 }) or Comment.find(:all, :params => { 'article_id' => 5, :page => 2 }) - -* Added find-one with symbol [David Heinemeier Hansson]. Example: Person.find(:one, :from => :leader) # => GET /people/leader.xml - -* BACKWARDS INCOMPATIBLE: Changed the finder API to be more extensible with :params and more strict usage of scopes [David Heinemeier Hansson]. Changes: - - Person.find(:all, :title => "CEO") ...becomes: Person.find(:all, :params => { :title => "CEO" }) - Person.find(:managers) ...becomes: Person.find(:all, :from => :managers) - Person.find("/companies/1/manager.xml") ...becomes: Person.find(:one, :from => "/companies/1/manager.xml") - -* Add support for setting custom headers per Active Resource model [Rick Olson] - - class Project - headers['X-Token'] = 'foo' - end - - # makes the GET request with the custom X-Token header - Project.find(:all) - -* Added find-by-path options to ActiveResource::Base.find [David Heinemeier Hansson]. Examples: - - employees = Person.find(:all, :from => "/companies/1/people.xml") # => GET /companies/1/people.xml - manager = Person.find("/companies/1/manager.xml") # => GET /companies/1/manager.xml - - -* Added support for using classes from within a single nested module [David Heinemeier Hansson]. Example: - - module Highrise - class Note < ActiveResource::Base - self.site = "http://37s.sunrise.i:3000" - end - - class Comment < ActiveResource::Base - self.site = "http://37s.sunrise.i:3000" - end - end - - assert_kind_of Highrise::Comment, Note.find(1).comments.first - - -* Added load_attributes_from_response as a way of loading attributes from other responses than just create [David Heinemeier Hansson] - - class Highrise::Task < ActiveResource::Base - def complete - load_attributes_from_response(post(:complete)) - end - end - - ...will set "done_at" when complete is called. - - -* Added support for calling custom methods #6979 [rwdaigle] - - Person.find(:managers) # => GET /people/managers.xml - Kase.find(1).post(:close) # => POST /kases/1/close.xml - -* Remove explicit prefix_options parameter for ActiveResource::Base#initialize. [Rick Olson] - ActiveResource splits the prefix_options from it automatically. - -* Allow ActiveResource::Base.delete with custom prefix. [Rick Olson] - -* Add ActiveResource::Base#dup [Rick Olson] - -* Fixed constant warning when fetching the same object multiple times [David Heinemeier Hansson] - -* Added that saves which get a body response (and not just a 201) will use that response to update themselves [David Heinemeier Hansson] - -* Disregard namespaces from the default element name, so Highrise::Person will just try to fetch from "/people", not "/highrise/people" [David Heinemeier Hansson] - -* Allow array and hash query parameters. #7756 [Greg Spurrier] - -* Loading a resource preserves its prefix_options. #7353 [Ryan Daigle] - -* Carry over the convenience of #create from ActiveRecord. Closes #7340. [Ryan Daigle] - -* Increase ActiveResource::Base test coverage. Closes #7173, #7174 [Rich Collins] - -* Interpret 422 Unprocessable Entity as ResourceInvalid. #7097 [dkubb] - -* Mega documentation patches. #7025, #7069 [rwdaigle] - -* Base.exists?(id, options) and Base#exists? check whether the resource is found. #6970 [rwdaigle] - -* Query string support. [untext, Jeremy Kemper] - # GET /forums/1/topics.xml?sort=created_at - Topic.find(:all, :forum_id => 1, :sort => 'created_at') - -* Base#==, eql?, and hash methods. == returns true if its argument is identical to self or if it's an instance of the same class, is not new?, and has the same id. eql? is an alias for ==. hash delegates to id. [Jeremy Kemper] - -* Allow subclassed resources to share the site info [Rick Olson, Jeremy Kemper] -d - class BeastResource < ActiveResource::Base - self.site = 'http://beast.caboo.se' - end - - class Forum < BeastResource - # taken from BeastResource - # self.site = 'http://beast.caboo.se' - end - - class Topic < BeastResource - self.site += '/forums/:forum_id' - end - -* Fix issues with ActiveResource collection handling. Closes #6291. [bmilekic] - -* Use attr_accessor_with_default to dry up attribute initialization. References #6538. [Stuart Halloway] - -* Add basic logging support for logging outgoing requests. [Jamis Buck] - -* Add Base.delete for deleting resources without having to instantiate them first. [Jamis Buck] - -* Make #save behavior mimic AR::Base#save (true on success, false on failure). [Jamis Buck] - -* Add Basic HTTP Authentication to ActiveResource (closes #6305). [jonathan] - -* Extracted #id_from_response as an entry point for customizing how a created resource gets its own ID. - By default, it extracts from the Location response header. - -* Optimistic locking: raise ActiveResource::ResourceConflict on 409 Conflict response. [Jeremy Kemper] - - # Example controller action - def update - @person.save! - rescue ActiveRecord::StaleObjectError - render :xml => @person.reload.to_xml, :status => '409 Conflict' - end - -* Basic validation support [Rick Olson] - - Parses the xml response of ActiveRecord::Errors#to_xml with a similar interface to ActiveRecord::Errors. - - render :xml => @person.errors.to_xml, :status => '400 Validation Error' - -* Deep hashes are converted into collections of resources. [Jeremy Kemper] - Person.new :name => 'Bob', - :address => { :id => 1, :city => 'Portland' }, - :contacts => [{ :id => 1 }, { :id => 2 }] - Looks for Address and Contact resources and creates them if unavailable. - So clients can fetch a complex resource in a single request if you e.g. - render :xml => @person.to_xml(:include => [:address, :contacts]) - in your controller action. - -* Major updates [Rick Olson] - - * Add full support for find/create/update/destroy - * Add support for specifying prefixes. - * Allow overriding of element_name, collection_name, and primary key - * Provide simpler HTTP mock interface for testing - - # rails routing code - map.resources :posts do |post| - post.resources :comments - end - - # ActiveResources - class Post < ActiveResource::Base - self.site = "http://37s.sunrise.i:3000/" - end - - class Comment < ActiveResource::Base - self.site = "http://37s.sunrise.i:3000/posts/:post_id/" - end - - @post = Post.find 5 - @comments = Comment.find :all, :post_id => @post.id - - @comment = Comment.new({:body => 'hello world'}, {:post_id => @post.id}) - @comment.save - -* Base.site= accepts URIs. 200...400 are valid response codes. PUT and POST request bodies default to ''. [Jeremy Kemper] - -* Initial checkin: object-oriented client for restful HTTP resources which follow the Rails convention. [David Heinemeier Hansson] diff --git a/activeresource/CHANGELOG.md b/activeresource/CHANGELOG.md new file mode 100644 index 0000000000..09d1eeb1c8 --- /dev/null +++ b/activeresource/CHANGELOG.md @@ -0,0 +1,334 @@ +## Rails 3.2.0 (unreleased) ## + +* Redirect responses: 303 See Other and 307 Temporary Redirect now behave like + 301 Moved Permanently and 302 Found. GH #3302. + + *Jim Herz* + + +## Rails 3.1.1 (October 7, 2011) ## + +* No changes. + + +## Rails 3.1.0 (August 30, 2011) ## + +* The default format has been changed to JSON for all requests. If you want to continue to use XML you will need to set `self.format = :xml` in the class. eg. + + class User < ActiveResource::Base self.format = :xml + end + +## Rails 3.0.7 (April 18, 2011) ## + +* No changes. + + +* Rails 3.0.6 (April 5, 2011) + +* No changes. + + +## Rails 3.0.5 (February 26, 2011) ## + +* No changes. + + +## Rails 3.0.4 (February 8, 2011) ## + +* No changes. + + +## Rails 3.0.3 (November 16, 2010) ## + +* No changes. + + +## Rails 3.0.2 (November 15, 2010) ## + +* No changes + + +## Rails 3.0.1 (October 15, 2010) ## + +* No Changes, just a version bump. + + +## Rails 3.0.0 (August 29, 2010) ## + +* JSON: set Base.include_root_in_json = true to include a root value in the JSON: {"post": {"title": ...}}. Mirrors the Active Record option. *Santiago Pastorino* + +* Add support for errors in JSON format. #1956 *Fabien Jakimowicz* + +* Recognizes 410 as Resource Gone. #2316 *Jordan Brough, Jatinder Singh* + +* More thorough SSL support. #2370 *Roy Nicholson* + +* HTTP proxy support. #2133 *Marshall Huss, Sébastien Dabet* + + +## 2.3.2 Final (March 15, 2009) ## + +* Nothing new, just included in 2.3.2 + + +## 2.2.1 RC2 (November 14th, 2008) ## + +* Fixed that ActiveResource#post would post an empty string when it shouldn't be posting anything #525 *Paolo Angelini* + + +## 2.2.0 RC1 (October 24th, 2008) ## + +* Add ActiveResource::Base#to_xml and ActiveResource::Base#to_json. #1011 *Rasik Pandey, Cody Fauser* + +* Add ActiveResource::Base.find(:last). [#754 state:resolved] (Adrian Mugnolo) + +* Fixed problems with the logger used if the logging string included %'s [#840 state:resolved] (Jamis Buck) + +* Fixed Base#exists? to check status code as integer [#299 state:resolved] (Wes Oldenbeuving) + + +## 2.1.0 (May 31st, 2008) ## + +* Fixed response logging to use length instead of the entire thing (seangeo) *#27* + +* Fixed that to_param should be used and honored instead of hardcoding the id #11406 *gspiers* + +* Improve documentation. *Ryan Bigg, Jan De Poorter, Cheah Chu Yeow, Xavier Shay, Jack Danger Canty, Emilio Tagua, Xavier Noria, Sunny Ripert* + +* Use HEAD instead of GET in exists? *bscofield* + +* Fix small documentation typo. Closes #10670 *Luca Guidi* + +* find_or_create_resource_for handles module nesting. #10646 *xavier* + +* Allow setting ActiveResource::Base#format before #site. *Rick Olson* + +* Support agnostic formats when calling custom methods. Closes #10635 *joerichsen* + +* Document custom methods. #10589 *Cheah Chu Yeow* + +* Ruby 1.9 compatibility. *Jeremy Kemper* + + +## 2.0.2 (December 16th, 2007) ## + +* Added more specific exceptions for 400, 401, and 403 (all descending from ClientError so existing rescues will work) #10326 *trek* + +* Correct empty response handling. #10445 *seangeo* + + +## 2.0.1 (December 7th, 2007) ## + +* Don't cache net/http object so that ActiveResource is more thread-safe. Closes #10142 *kou* + +* Update XML documentation examples to include explicit type attributes. Closes #9754 *Josh Susser* + +* Added one-off declarations of mock behavior [David Heinemeier Hansson]. Example: + + Before: + ActiveResource::HttpMock.respond_to do |mock| + mock.get "/people/1.xml", {}, "<person><name>David</name></person>" + end + + Now: + ActiveResource::HttpMock.respond_to.get "/people/1.xml", {}, "<person><name>David</name></person>" + +* Added ActiveResource.format= which defaults to :xml but can also be set to :json [David Heinemeier Hansson]. Example: + + class Person < ActiveResource::Base + self.site = "http://app/" + self.format = :json + end + + person = Person.find(1) # => GET http://app/people/1.json + person.name = "David" + person.save # => PUT http://app/people/1.json {name: "David"} + + Person.format = :xml + person.name = "Mary" + person.save # => PUT http://app/people/1.json <person><name>Mary</name></person> + +* Fix reload error when path prefix is used. #8727 *Ian Warshak* + +* Remove ActiveResource::Struct because it hasn't proven very useful. Creating a new ActiveResource::Base subclass is often less code and always clearer. #8612 *Josh Peek* + +* Fix query methods on resources. *Cody Fauser* + +* pass the prefix_options to the instantiated record when using find without a specific id. Closes #8544 *Eloy Duran* + +* Recognize and raise an exception on 405 Method Not Allowed responses. #7692 *Josh Peek* + +* Handle string and symbol param keys when splitting params into prefix params and query params. + + Comment.find(:all, :params => { :article_id => 5, :page => 2 }) or Comment.find(:all, :params => { 'article_id' => 5, :page => 2 }) + +* Added find-one with symbol [David Heinemeier Hansson]. Example: Person.find(:one, :from => :leader) # => GET /people/leader.xml + +* BACKWARDS INCOMPATIBLE: Changed the finder API to be more extensible with :params and more strict usage of scopes [David Heinemeier Hansson]. Changes: + + Person.find(:all, :title => "CEO") ...becomes: Person.find(:all, :params => { :title => "CEO" }) + Person.find(:managers) ...becomes: Person.find(:all, :from => :managers) + Person.find("/companies/1/manager.xml") ...becomes: Person.find(:one, :from => "/companies/1/manager.xml") + +* Add support for setting custom headers per Active Resource model *Rick Olson* + + class Project + headers['X-Token'] = 'foo' + end + + \# makes the GET request with the custom X-Token header + Project.find(:all) + +* Added find-by-path options to ActiveResource::Base.find [David Heinemeier Hansson]. Examples: + + employees = Person.find(:all, :from => "/companies/1/people.xml") # => GET /companies/1/people.xml + manager = Person.find("/companies/1/manager.xml") # => GET /companies/1/manager.xml + + +* Added support for using classes from within a single nested module [David Heinemeier Hansson]. Example: + + module Highrise + class Note < ActiveResource::Base + self.site = "http://37s.sunrise.i:3000" + end + + class Comment < ActiveResource::Base + self.site = "http://37s.sunrise.i:3000" + end + end + + assert_kind_of Highrise::Comment, Note.find(1).comments.first + + +* Added load_attributes_from_response as a way of loading attributes from other responses than just create *David Heinemeier Hansson* + + class Highrise::Task < ActiveResource::Base + def complete + load_attributes_from_response(post(:complete)) + end + end + + ...will set "done_at" when complete is called. + + +* Added support for calling custom methods #6979 *rwdaigle* + + Person.find(:managers) # => GET /people/managers.xml + Kase.find(1).post(:close) # => POST /kases/1/close.xml + +* Remove explicit prefix_options parameter for ActiveResource::Base#initialize. *Rick Olson* + ActiveResource splits the prefix_options from it automatically. + +* Allow ActiveResource::Base.delete with custom prefix. *Rick Olson* + +* Add ActiveResource::Base#dup *Rick Olson* + +* Fixed constant warning when fetching the same object multiple times *David Heinemeier Hansson* + +* Added that saves which get a body response (and not just a 201) will use that response to update themselves *David Heinemeier Hansson* + +* Disregard namespaces from the default element name, so Highrise::Person will just try to fetch from "/people", not "/highrise/people" *David Heinemeier Hansson* + +* Allow array and hash query parameters. #7756 *Greg Spurrier* + +* Loading a resource preserves its prefix_options. #7353 *Ryan Daigle* + +* Carry over the convenience of #create from ActiveRecord. Closes #7340. *Ryan Daigle* + +* Increase ActiveResource::Base test coverage. Closes #7173, #7174 *Rich Collins* + +* Interpret 422 Unprocessable Entity as ResourceInvalid. #7097 *dkubb* + +* Mega documentation patches. #7025, #7069 *rwdaigle* + +* Base.exists?(id, options) and Base#exists? check whether the resource is found. #6970 *rwdaigle* + +* Query string support. *untext, Jeremy Kemper* + # GET /forums/1/topics.xml?sort=created_at + Topic.find(:all, :forum_id => 1, :sort => 'created_at') + +* Base#==, eql?, and hash methods. == returns true if its argument is identical to self or if it's an instance of the same class, is not new?, and has the same id. eql? is an alias for ==. hash delegates to id. *Jeremy Kemper* + +* Allow subclassed resources to share the site info *Rick Olson, Jeremy Kemper* + d class BeastResource < ActiveResource::Base + self.site = 'http://beast.caboo.se' + end + + class Forum < BeastResource + # taken from BeastResource + # self.site = 'http://beast.caboo.se' + end + + class Topic < BeastResource + self.site += '/forums/:forum_id' + end + +* Fix issues with ActiveResource collection handling. Closes #6291. *bmilekic* + +* Use attr_accessor_with_default to dry up attribute initialization. References #6538. *Stuart Halloway* + +* Add basic logging support for logging outgoing requests. *Jamis Buck* + +* Add Base.delete for deleting resources without having to instantiate them first. *Jamis Buck* + +* Make #save behavior mimic AR::Base#save (true on success, false on failure). *Jamis Buck* + +* Add Basic HTTP Authentication to ActiveResource (closes #6305). *jonathan* + +* Extracted #id_from_response as an entry point for customizing how a created resource gets its own ID. + By default, it extracts from the Location response header. + +* Optimistic locking: raise ActiveResource::ResourceConflict on 409 Conflict response. *Jeremy Kemper* + + # Example controller action + def update + @person.save! + rescue ActiveRecord::StaleObjectError + render :xml => @person.reload.to_xml, :status => '409 Conflict' + end + +* Basic validation support *Rick Olson* + + Parses the xml response of ActiveRecord::Errors#to_xml with a similar interface to ActiveRecord::Errors. + + render :xml => @person.errors.to_xml, :status => '400 Validation Error' + +* Deep hashes are converted into collections of resources. *Jeremy Kemper* + Person.new :name => 'Bob', + :address => { :id => 1, :city => 'Portland' }, + :contacts => [{ :id => 1 }, { :id => 2 }] + Looks for Address and Contact resources and creates them if unavailable. + So clients can fetch a complex resource in a single request if you e.g. + render :xml => @person.to_xml(:include => [:address, :contacts]) + in your controller action. + +* Major updates *Rick Olson* + + * Add full support for find/create/update/destroy + * Add support for specifying prefixes. + * Allow overriding of element_name, collection_name, and primary key + * Provide simpler HTTP mock interface for testing + + # rails routing code + map.resources :posts do |post| + post.resources :comments + end + + # ActiveResources + class Post < ActiveResource::Base + self.site = "http://37s.sunrise.i:3000/" + end + + class Comment < ActiveResource::Base + self.site = "http://37s.sunrise.i:3000/posts/:post_id/" + end + + @post = Post.find 5 + @comments = Comment.find :all, :post_id => @post.id + + @comment = Comment.new({:body => 'hello world'}, {:post_id => @post.id}) + @comment.save + +* Base.site= accepts URIs. 200...400 are valid response codes. PUT and POST request bodies default to ''. *Jeremy Kemper* + +* Initial checkin: object-oriented client for restful HTTP resources which follow the Rails convention. *David Heinemeier Hansson* diff --git a/activeresource/README.rdoc b/activeresource/README.rdoc index b03e8c4c25..c86289c5fe 100644 --- a/activeresource/README.rdoc +++ b/activeresource/README.rdoc @@ -22,13 +22,13 @@ received and serialized into a usable Ruby object. == Download and installation -The latest version of Active Support can be installed with Rubygems: +The latest version of Active Support can be installed with RubyGems: % [sudo] gem install activeresource Source code can be downloaded as part of the Rails project on GitHub -* https://github.com/rails/rails/tree/master/activeresource/ +* https://github.com/rails/rails/tree/master/activeresource === Configuration and Usage @@ -36,7 +36,7 @@ Putting Active Resource to use is very similar to Active Record. It's as simple that inherits from ActiveResource::Base and providing a <tt>site</tt> class variable to it: class Person < ActiveResource::Base - self.site = "http://api.people.com:3000/" + self.site = "http://api.people.com:3000" end Now the Person class is REST enabled and can invoke REST services very similarly to how Active Record invokes @@ -135,8 +135,8 @@ as the id of the ARes object. ==== Update -'save' is also used to update an existing resource - and follows the same protocol as creating a resource -with the exception that no response headers are needed - just an empty response when the update on the +'save' is also used to update an existing resource and follows the same protocol as creating a resource +with the exception that no response headers are needed -- just an empty response when the update on the server side was successful. # <person><first>Ryan</first></person> diff --git a/activeresource/activeresource.gemspec b/activeresource/activeresource.gemspec index a8772ecf8c..f5c26f38df 100644 --- a/activeresource/activeresource.gemspec +++ b/activeresource/activeresource.gemspec @@ -13,7 +13,7 @@ Gem::Specification.new do |s| s.email = 'david@loudthinking.com' s.homepage = 'http://www.rubyonrails.org' - s.files = Dir['CHANGELOG', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*'] + s.files = Dir['CHANGELOG.md', 'MIT-LICENSE', 'README.rdoc', 'examples/**/*', 'lib/**/*'] s.require_path = 'lib' s.extra_rdoc_files = %w( README.rdoc ) diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index 693bd0592e..10cc727bd9 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -170,8 +170,8 @@ module ActiveResource # <tt>404</tt> is just one of the HTTP error response codes that Active Resource will handle with its own exception. The # following HTTP response codes will also result in these exceptions: # - # * 200..399 - Valid response, no exception (other than 301, 302) - # * 301, 302 - ActiveResource::Redirection + # * 200..399 - Valid response. No exceptions, other than these redirects: + # * 301, 302, 303, 307 - ActiveResource::Redirection # * 400 - ActiveResource::BadRequest # * 401 - ActiveResource::UnauthorizedAccess # * 403 - ActiveResource::ForbiddenAccess @@ -637,6 +637,10 @@ module ActiveResource # Post.element_path(1) # # => /posts/1.json # + # class Comment < ActiveResource::Base + # self.site = "http://37s.sunrise.i/posts/:post_id/" + # end + # # Comment.element_path(1, :post_id => 5) # # => /posts/5/comments/1.json # @@ -663,6 +667,10 @@ module ActiveResource # Post.new_element_path # # => /posts/new.json # + # class Comment < ActiveResource::Base + # self.site = "http://37s.sunrise.i/posts/:post_id/" + # end + # # Comment.collection_path(:post_id => 5) # # => /posts/5/comments/new.json def new_element_path(prefix_options = {}) @@ -955,7 +963,7 @@ module ActiveResource prefix_options, query_options = {}, {} (options || {}).each do |key, value| - next if key.blank? + next if key.blank? || !key.respond_to?(:to_sym) (prefix_parameters.include?(key.to_sym) ? prefix_options : query_options)[key.to_sym] = value end @@ -1357,7 +1365,9 @@ module ActiveResource end def load_attributes_from_response(response) - if !response['Content-Length'].blank? && response['Content-Length'] != "0" && !response.body.nil? && response.body.strip.size > 0 + if (response_code_allows_body?(response.code) && + (response['Content-Length'].nil? || response['Content-Length'] != "0") && + !response.body.nil? && response.body.strip.size > 0) load(self.class.format.decode(response.body), true) @persisted = true end @@ -1381,6 +1391,16 @@ module ActiveResource end private + + def read_attribute_for_serialization(n) + attributes[n] + end + + # Determine whether the response is allowed to have a body per HTTP 1.1 spec section 4.4.1 + def response_code_allows_body?(c) + !((100..199).include?(c) || [204,304].include?(c)) + end + # Tries to find a resource for a given collection name; if it fails, then the resource is created def find_or_create_resource_for_collection(name) find_or_create_resource_for(ActiveSupport::Inflector.singularize(name.to_s)) diff --git a/activeresource/lib/active_resource/connection.rb b/activeresource/lib/active_resource/connection.rb index d923204dde..94839c8c25 100644 --- a/activeresource/lib/active_resource/connection.rb +++ b/activeresource/lib/active_resource/connection.rb @@ -122,7 +122,7 @@ module ActiveResource # Handles response and error codes from the remote service. def handle_response(response) case response.code.to_i - when 301,302 + when 301, 302, 303, 307 raise(Redirection.new(response)) when 200...400 response @@ -238,8 +238,11 @@ module ActiveResource def digest_auth_header(http_method, uri) params = extract_params_from_response + request_uri = uri.path + request_uri << "?#{uri.query}" if uri.query + ha1 = Digest::MD5.hexdigest("#{@user}:#{params['realm']}:#{@password}") - ha2 = Digest::MD5.hexdigest("#{http_method.to_s.upcase}:#{uri.path}") + ha2 = Digest::MD5.hexdigest("#{http_method.to_s.upcase}:#{request_uri}") params.merge!('cnonce' => client_nonce) request_digest = Digest::MD5.hexdigest([ha1, params['nonce'], "0", params['cnonce'], params['qop'], ha2].join(":")) diff --git a/activeresource/lib/active_resource/custom_methods.rb b/activeresource/lib/active_resource/custom_methods.rb index c1931b2758..2a651dd48e 100644 --- a/activeresource/lib/active_resource/custom_methods.rb +++ b/activeresource/lib/active_resource/custom_methods.rb @@ -23,7 +23,7 @@ module ActiveResource # self.site = "http://37s.sunrise.i:3000" # end # - # Person.new(:name => 'Ryan).post(:register) # POST /people/new/register.json + # Person.new(:name => 'Ryan').post(:register) # POST /people/new/register.json # # => { :id => 1, :name => 'Ryan' } # # Person.find(1).put(:promote, :position => 'Manager') # PUT /people/1/promote.json @@ -85,37 +85,35 @@ module ActiveResource end end - module InstanceMethods - def get(method_name, options = {}) - self.class.format.decode(connection.get(custom_method_element_url(method_name, options), self.class.headers).body) - end + def get(method_name, options = {}) + self.class.format.decode(connection.get(custom_method_element_url(method_name, options), self.class.headers).body) + end - def post(method_name, options = {}, body = nil) - request_body = body.blank? ? encode : body - if new? - connection.post(custom_method_new_element_url(method_name, options), request_body, self.class.headers) - else - connection.post(custom_method_element_url(method_name, options), request_body, self.class.headers) - end + def post(method_name, options = {}, body = nil) + request_body = body.blank? ? encode : body + if new? + connection.post(custom_method_new_element_url(method_name, options), request_body, self.class.headers) + else + connection.post(custom_method_element_url(method_name, options), request_body, self.class.headers) end + end - def put(method_name, options = {}, body = '') - connection.put(custom_method_element_url(method_name, options), body, self.class.headers) - end + def put(method_name, options = {}, body = '') + connection.put(custom_method_element_url(method_name, options), body, self.class.headers) + end - def delete(method_name, options = {}) - connection.delete(custom_method_element_url(method_name, options), self.class.headers) - end + def delete(method_name, options = {}) + connection.delete(custom_method_element_url(method_name, options), self.class.headers) + end - private - def custom_method_element_url(method_name, options = {}) - "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}" - end + private + def custom_method_element_url(method_name, options = {}) + "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/#{id}/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}" + end - def custom_method_new_element_url(method_name, options = {}) - "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}" - end - end + def custom_method_new_element_url(method_name, options = {}) + "#{self.class.prefix(prefix_options)}#{self.class.collection_name}/new/#{method_name}.#{self.class.format.extension}#{self.class.__send__(:query_string, options)}" + end end end diff --git a/activeresource/lib/active_resource/exceptions.rb b/activeresource/lib/active_resource/exceptions.rb index 6b953b28ad..51bede3bd0 100644 --- a/activeresource/lib/active_resource/exceptions.rb +++ b/activeresource/lib/active_resource/exceptions.rb @@ -33,35 +33,45 @@ module ActiveResource # 3xx Redirection class Redirection < ConnectionError # :nodoc: - def to_s; response['Location'] ? "#{super} => #{response['Location']}" : super; end + def to_s + response['Location'] ? "#{super} => #{response['Location']}" : super + end end - # Raised when ... - class MissingPrefixParam < ArgumentError; end # :nodoc: + class MissingPrefixParam < ArgumentError # :nodoc: + end # 4xx Client Error - class ClientError < ConnectionError; end # :nodoc: + class ClientError < ConnectionError # :nodoc: + end # 400 Bad Request - class BadRequest < ClientError; end # :nodoc + class BadRequest < ClientError # :nodoc: + end # 401 Unauthorized - class UnauthorizedAccess < ClientError; end # :nodoc + class UnauthorizedAccess < ClientError # :nodoc: + end # 403 Forbidden - class ForbiddenAccess < ClientError; end # :nodoc + class ForbiddenAccess < ClientError # :nodoc: + end # 404 Not Found - class ResourceNotFound < ClientError; end # :nodoc: + class ResourceNotFound < ClientError # :nodoc: + end # 409 Conflict - class ResourceConflict < ClientError; end # :nodoc: + class ResourceConflict < ClientError # :nodoc: + end # 410 Gone - class ResourceGone < ClientError; end # :nodoc: + class ResourceGone < ClientError # :nodoc: + end # 5xx Server Error - class ServerError < ConnectionError; end # :nodoc: + class ServerError < ConnectionError # :nodoc: + end # 405 Method Not Allowed class MethodNotAllowed < ClientError # :nodoc: diff --git a/activeresource/test/cases/authorization_test.rb b/activeresource/test/cases/authorization_test.rb index 69ef9a2821..17cd9b30fc 100644 --- a/activeresource/test/cases/authorization_test.rb +++ b/activeresource/test/cases/authorization_test.rb @@ -131,6 +131,12 @@ class AuthorizationTest < Test::Unit::TestCase assert_equal blank_digest_auth_header("/people/2.json", "fad396f6a34aeba28e28b9b96ddbb671"), authorization_header['Authorization'] end + def test_authorization_header_with_query_string_if_auth_type_is_digest + @authenticated_conn.auth_type = :digest + authorization_header = @authenticated_conn.__send__(:authorization_header, :get, URI.parse('/people/2.json?only=name')) + assert_equal blank_digest_auth_header("/people/2.json?only=name", "f8457b0b5d21b6b80737a386217afb24"), authorization_header['Authorization'] + end + def test_get david = decode(@authenticated_conn.get("/people/2.json")) assert_equal "David", david["name"] diff --git a/activeresource/test/cases/base/load_test.rb b/activeresource/test/cases/base/load_test.rb index 0d030148d0..784e7dd036 100644 --- a/activeresource/test/cases/base/load_test.rb +++ b/activeresource/test/cases/base/load_test.rb @@ -51,9 +51,28 @@ class BaseLoadTest < Test::Unit::TestCase :votes => [ true, false, true ], :places => [ "Columbia City", "Unknown" ]}}} + + # List of books formated as [{timestamp_of_publication => name}, ...] + @books = {:books => [ + {1009839600 => "Ruby in a Nutshell"}, + {1199142000 => "The Ruby Programming Language"} + ]} + + @books_date = {:books => [ + {Time.at(1009839600) => "Ruby in a Nutshell"}, + {Time.at(1199142000) => "The Ruby Programming Language"} + ]} @person = Person.new end + def test_load_hash_with_integers_as_keys + assert_nothing_raised{@person.load(@books)} + end + + def test_load_hash_with_dates_as_keys + assert_nothing_raised{@person.load(@books_date)} + end + def test_load_expects_hash assert_raise(ArgumentError) { @person.load nil } assert_raise(ArgumentError) { @person.load '<person id="1"/>' } diff --git a/activeresource/test/cases/base_test.rb b/activeresource/test/cases/base_test.rb index f45652d988..7b42f64a35 100644 --- a/activeresource/test/cases/base_test.rb +++ b/activeresource/test/cases/base_test.rb @@ -636,13 +636,37 @@ class BaseTest < Test::Unit::TestCase assert_nil p.__send__(:id_from_response, resp) end - def test_load_attributes_from_response - p = Person.new + def test_not_persisted_with_no_body_and_positive_content_length resp = ActiveResource::Response.new(nil) resp['Content-Length'] = "100" - assert_nil p.__send__(:load_attributes_from_response, resp) + Person.connection.expects(:post).returns(resp) + assert !Person.create.persisted? + end + + def test_not_persisted_with_body_and_zero_content_length + resp = ActiveResource::Response.new(@rick) + resp['Content-Length'] = "0" + Person.connection.expects(:post).returns(resp) + assert !Person.create.persisted? end + # These response codes aren't allowed to have bodies per HTTP spec + def test_not_persisted_with_empty_response_codes + [100,101,204,304].each do |status_code| + resp = ActiveResource::Response.new(@rick, status_code) + Person.connection.expects(:post).returns(resp) + assert !Person.create.persisted? + end + end + + # Content-Length is not required by HTTP 1.1, so we should read + # the body anyway in its absence. + def test_persisted_with_no_content_length + resp = ActiveResource::Response.new(@rick) + resp['Content-Length'] = nil + Person.connection.expects(:post).returns(resp) + assert Person.create.persisted? + end def test_create_with_custom_prefix matzs_house = StreetAddress.new(:person_id => 1) @@ -980,9 +1004,17 @@ class BaseTest < Test::Unit::TestCase def test_to_xml_with_private_method_name_as_attribute Person.format = :xml - assert_nothing_raised(ArgumentError) { - Customer.new(:test => true).to_xml - } + + customer = Customer.new(:foo => "foo") + customer.singleton_class.class_eval do + def foo + "bar" + end + private :foo + end + + assert !customer.to_xml.include?("<foo>bar</foo>") + assert customer.to_xml.include?("<foo>foo</foo>") ensure Person.format = :json end diff --git a/activeresource/test/cases/connection_test.rb b/activeresource/test/cases/connection_test.rb index 09df0fb678..535107aeef 100644 --- a/activeresource/test/cases/connection_test.rb +++ b/activeresource/test/cases/connection_test.rb @@ -2,6 +2,7 @@ require 'abstract_unit' class ConnectionTest < Test::Unit::TestCase ResponseCodeStub = Struct.new(:code) + RedirectResponseStub = Struct.new(:code, :Location) def setup @conn = ActiveResource::Connection.new('http://localhost') @@ -38,6 +39,18 @@ class ConnectionTest < Test::Unit::TestCase assert_equal expected, handle_response(expected) end + # 301 is moved permanently (redirect) + assert_redirect_raises 301 + + # 302 is found (redirect) + assert_redirect_raises 302 + + # 303 is see other (redirect) + assert_redirect_raises 303 + + # 307 is temporary redirect + assert_redirect_raises 307 + # 400 is a bad request (e.g. malformed URI or missing request parameter) assert_response_raises ActiveResource::BadRequest, 400 @@ -247,6 +260,12 @@ class ConnectionTest < Test::Unit::TestCase end end + def assert_redirect_raises(code) + assert_raise(ActiveResource::Redirection, "Expected response code #{code} to raise ActiveResource::Redirection") do + handle_response RedirectResponseStub.new(code, 'http://example.com/') + end + end + def handle_response(response) @conn.__send__(:handle_response, response) end |