Permalink
Browse files

Ease restrictions on calling implicit HTTP methods

Allows calling POST/PUT/DELETE etc on relations
that don't explicitly define them.
  • Loading branch information...
1 parent b35f456 commit 6145aaec160a3fc12d5e3b0cb1c663d9d501f992 @pengwynn pengwynn committed Nov 6, 2012
Showing with 34 additions and 1 deletion.
  1. +6 −0 lib/sawyer/agent.rb
  2. +1 −1 lib/sawyer/relation.rb
  3. +27 −0 test/relation_test.rb
View
@@ -6,6 +6,7 @@ class Agent
NO_BODY = Set.new([:get, :head])
attr_accessor :links_parser
+ attr_accessor :allow_undefined_methods
class << self
attr_writer :serializer
@@ -38,6 +39,7 @@ def initialize(endpoint, options = nil)
@conn = (options && options[:faraday]) || Faraday.new
@serializer = (options && options[:serializer]) || self.class.serializer
@links_parser = (options && options[:links_parser]) || HalLinksParser.new
+ @allow_undefined_methods = (options && options[:allow_undefined_methods])
@conn.url_prefix = @endpoint
yield @conn if block_given?
end
@@ -129,6 +131,10 @@ def expand_url(url, options = nil)
options ? expand.call(options) : expand.call
end
+ def allow_undefined_methods?
+ !!@allow_undefined_methods
+ end
+
def inspect
%(<#{self.class} #{@endpoint}>)
end
@@ -253,7 +253,7 @@ def href(options = nil)
# Returns a Sawyer::Response.
def call(data = nil, options = nil)
m = options && options[:method]
- if m && !@available_methods.include?(m == :head ? :get : m)
+ if m && !@agent.allow_undefined_methods? && !@available_methods.include?(m == :head ? :get : m)
raise ArgumentError, "method #{m.inspect} is not available: #{@available_methods.to_a.inspect}"
end
View
@@ -134,6 +134,33 @@ def test_handles_invalid_uri
assert_equal :self, rel.name
assert_equal '/this has spaces', rel.href
end
+
+ def test_allows_all_methods_when_not_in_strict_mode
+
+ agent = Sawyer::Agent.new "http://foo.com/a/", :allow_undefined_methods => true do |conn|
+ conn.builder.handlers.delete(Faraday::Adapter::NetHttp)
+ conn.adapter :test do |stubs|
+ stubs.get '/a/1' do
+ [200, {}, '{}']
+ end
+ stubs.delete '/a/1' do
+ [204, {}, '{}']
+ end
+ stubs.post '/a/1' do
+ [200, {}, '{}']
+ end
+ stubs.put '/a/1' do
+ [204, {}, '{}']
+ end
+ end
+ end
+
+ rel = Sawyer::Relation.new agent, :self, "/a/1"
+ assert_equal 200, rel.get.status
+ assert_equal 200, rel.post.status
+ assert_equal 204, rel.put.status
+ assert_equal 204, rel.delete.status
+ end
end
end

0 comments on commit 6145aae

Please sign in to comment.