diff --git a/history.md b/history.md index a721eaa..292f4e8 100644 --- a/history.md +++ b/history.md @@ -3,6 +3,7 @@ - add response body in Exception#inspect - add support for RestClient.options - fix tests for 1.9.2 (patch provided by Niko Dittmann) +- block passing in Resource#[] (patch provided by Niko Dittmann) # 1.6.0 diff --git a/lib/restclient/resource.rb b/lib/restclient/resource.rb index 6d551a2..31d18a8 100644 --- a/lib/restclient/resource.rb +++ b/lib/restclient/resource.rb @@ -130,8 +130,13 @@ module RestClient # comments = first_post['comments'] # comments.post 'Hello', :content_type => 'text/plain' # - def [](suburl) - self.class.new(concat_urls(url, suburl), options) + def [](suburl, &new_block) + case + when block_given? then self.class.new(concat_urls(url, suburl), options, &new_block) + when block then self.class.new(concat_urls(url, suburl), options, &block) + else + self.class.new(concat_urls(url, suburl), options) + end end def concat_urls(url, suburl) # :nodoc: diff --git a/spec/base.rb b/spec/base.rb index 51fba66..965a6e2 100644 --- a/spec/base.rb +++ b/spec/base.rb @@ -1,4 +1,8 @@ -Encoding.default_internal = Encoding.default_external = "ASCII-8BIT" if RUBY_VERSION == '1.9.1' or RUBY_VERSION == '1.9.2' +def is_ruby_19? + RUBY_VERSION == '1.9.1' or RUBY_VERSION == '1.9.2' +end + +Encoding.default_internal = Encoding.default_external = "ASCII-8BIT" if is_ruby_19? require 'rubygems' require 'spec' diff --git a/spec/resource_spec.rb b/spec/resource_spec.rb index c833982..18fadbc 100644 --- a/spec/resource_spec.rb +++ b/spec/resource_spec.rb @@ -72,6 +72,31 @@ describe RestClient::Resource do parent['posts'].password.should == 'password' end + it "passes a given block to subresources" do + block = Proc.new{|r| r} + parent = RestClient::Resource.new('http://example.com', &block) + parent['posts'].block.should == block + end + + it "the block should be overrideable" do + block1 = Proc.new{|r| r} + block2 = Proc.new{|r| r} + parent = RestClient::Resource.new('http://example.com', &block1) + # parent['posts', &block2].block.should == block2 # ruby 1.9 syntax + parent.send(:[], 'posts', &block2).block.should == block2 + end + + it "the block should be overrideable in ruby 1.9 syntax" do + block = Proc.new{|r| r} + parent = RestClient::Resource.new('http://example.com', &block) + r19_syntax = %q{ + parent['posts', &->(r){r}].block.should_not == block + } + is_ruby_19? + eval(r19_syntax) + end + end + it "prints its url with to_s" do RestClient::Resource.new('x').to_s.should == 'x' end