]> git.donarmstrong.com Git - dsa-puppet.git/blob - 3rdparty/modules/aviator/feature/faraday/response.rb
Revert "add stackforge/keystone to 3rdparty"
[dsa-puppet.git] / 3rdparty / modules / aviator / feature / faraday / response.rb
1 require 'forwardable'
2
3 module Faraday
4   class Response
5     # Used for simple response middleware.
6     class Middleware < Faraday::Middleware
7       def call(env)
8         @app.call(env).on_complete do |environment|
9           on_complete(environment)
10         end
11       end
12
13       # Override this to modify the environment after the response has finished.
14       # Calls the `parse` method if defined
15       def on_complete(env)
16         env.body = parse(env.body) if respond_to?(:parse) && env.parse_body?
17       end
18     end
19
20     extend Forwardable
21     extend MiddlewareRegistry
22
23     register_middleware File.expand_path('../response', __FILE__),
24       :raise_error => [:RaiseError, 'raise_error'],
25       :logger => [:Logger, 'logger']
26
27     def initialize(env = nil)
28       @env = Env.from(env) if env
29       @on_complete_callbacks = []
30     end
31
32     attr_reader :env
33
34     def_delegators :env, :to_hash
35
36     def status
37       finished? ? env.status : nil
38     end
39
40     def headers
41       finished? ? env.response_headers : {}
42     end
43     def_delegator :headers, :[]
44
45     def body
46       finished? ? env.body : nil
47     end
48
49     def finished?
50       !!env
51     end
52
53     def on_complete
54       if not finished?
55         @on_complete_callbacks << Proc.new
56       else
57         yield(env)
58       end
59       return self
60     end
61
62     def finish(env)
63       raise "response already finished" if finished?
64       @on_complete_callbacks.each { |callback| callback.call(env) }
65       @env = Env.from(env)
66       return self
67     end
68
69     def success?
70       finished? && env.success?
71     end
72
73     # because @on_complete_callbacks cannot be marshalled
74     def marshal_dump
75       !finished? ? nil : {
76         :status => @env.status, :body => @env.body,
77         :response_headers => @env.response_headers
78       }
79     end
80
81     def marshal_load(env)
82       @env = Env.from(env)
83     end
84
85     # Expand the env with more properties, without overriding existing ones.
86     # Useful for applying request params after restoring a marshalled Response.
87     def apply_request(request_env)
88       raise "response didn't finish yet" unless finished?
89       @env = Env.from(request_env).update(@env)
90       return self
91     end
92   end
93 end