Class: Apis::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/apis/connection.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Connection

Returns a new instance of Connection.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/apis/connection.rb', line 5

def initialize(options = {})
  @scope = Apis::ConnectionScope.new
  @scope.headers, @scope.params = {}, {}

  if String === options
    self.uri = options
  else
    options.each do |key, value|
      send("#{key}=", value) if respond_to?("#{key}=")
    end
  end

  if block_given?
    block = Proc.new
    instance_eval(&block)
  end
  adapter(Apis::Adapter.default) unless @adapter
end

Instance Method Details

#adapter(value = nil) ⇒ Object



60
61
62
63
64
65
66
67
# File 'lib/apis/connection.rb', line 60

def adapter(value = nil)
  if Symbol === value
    value = Apis::Adapter.lookup(value)
  end

  @adapter = value.new(:uri => uri) if value
  @adapter
end

#headersObject



32
33
34
# File 'lib/apis/connection.rb', line 32

def headers
  @scope.headers
end

#headers=(value) ⇒ Object



36
37
38
# File 'lib/apis/connection.rb', line 36

def headers=(value)
  @scope.headers.merge!(value)
end

#paramsObject



40
41
42
# File 'lib/apis/connection.rb', line 40

def params
  @scope.params
end

#params=(value) ⇒ Object



44
45
46
# File 'lib/apis/connection.rb', line 44

def params=(value)
  @scope.params.merge!(value)
end

#requestObject



48
49
50
51
52
# File 'lib/apis/connection.rb', line 48

def request
  block = block_given? ? Proc.new : nil
  @request ||= Apis::Builder.new(:lookup_context => Apis::Middleware::Request, &block)
  @request
end

#responseObject



54
55
56
57
58
# File 'lib/apis/connection.rb', line 54

def response
  block = block_given? ? Proc.new : nil
  @response ||= Apis::Builder.new(:lookup_context => Apis::Middleware::Response, &block)
  @response
end

#run_request(method, path = nil, params = {}, headers = {}, &block) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/apis/connection.rb', line 77

def run_request(method, path = nil, params = {}, headers = {}, &block)
  #block = block_given? ? Proc.new : nil
  # TODO: refactor this, it's ugly
  @scope.scoped do
    self.params = params if params
    self.headers = headers if headers
    block.call(self) if block
    path ||= uri.path.empty? ? '/' : uri.path
    self.request.to_app.call(
      :method => method,
      :params => self.params,
      :headers => self.headers
    ) unless self.request.to_a.empty?
    res = Apis::Response.new(*adapter.run(method, path, self.params, self.headers))
    self.response.to_app.call(res) unless self.response.to_a.empty?
    res
  end
end

#uriObject



24
25
26
# File 'lib/apis/connection.rb', line 24

def uri
  @scope.uri
end

#uri=(value) ⇒ Object



28
29
30
# File 'lib/apis/connection.rb', line 28

def uri=(value)
  @scope.uri = Addressable::URI.parse(value)
end