Class: Grac::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/grac/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri, options = {}) ⇒ Client

Returns a new instance of Client.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/grac/client.rb', line 13

def initialize(uri, options = {})
  URI.parse(uri)

  @uri = uri
  @options = {
    :connecttimeout => options[:connecttimeout] || 0.1,
    :timeout        => options[:timeout]        || 15,
    :params         => options[:params]         || {},
    :headers        => {
      "User-Agent"   => "Grac v#{Grac::VERSION}",
      "Content-Type" => "application/json;charset=utf-8"
    }.merge(options[:headers] || {}),
    :postprocessing => options[:postprocessing] || {},
    :middleware     => options[:middleware]     || []
  }
  @options.freeze
  [:params, :headers, :postprocessing, :middleware].each do |k|
    @options[k].freeze
  end
  @uri.freeze
end

Instance Attribute Details

#uriObject (readonly)

Returns the value of attribute uri.



11
12
13
# File 'lib/grac/client.rb', line 11

def uri
  @uri
end

Instance Method Details

#call(opts, request_uri, method, params, body) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/grac/client.rb', line 65

def call(opts, request_uri, method, params, body)
  request_hash = {
    :method         => method,
    :params         => params,  # Query params are escaped by Typhoeus
    :body           => body,
    :connecttimeout => opts[:connecttimeout],
    :timeout        => opts[:timeout],
    :headers        => opts[:headers]
  }

  request  = ::Typhoeus::Request.new(request_uri, request_hash)
  response = request.run

  # Retry GET and HEAD requests - modifying requests might not be idempotent
  response = request.run if response.timed_out? && ['get', 'head'].include?(method)

  # A request can time out while receiving data. In this case response.code might indicate
  # success although data hasn't been fully transferred. Thus rely on Typhoeus for
  # detecting a timeout.
  if response.timed_out?
    raise Exception::ServiceTimeout.new(method, request.url, response.return_message)
  end

  return Response.new(response)
end

#path(path, variables = {}) ⇒ Object



44
45
46
47
48
49
# File 'lib/grac/client.rb', line 44

def path(path, variables = {})
  variables.each do |key, value|
    path = path.gsub("{#{key}}", escape_url_param(value))
  end
  self.class.new("#{@uri}#{path}", @options)
end

#set(options = {}) ⇒ Object



35
36
37
38
39
40
41
42
# File 'lib/grac/client.rb', line 35

def set(options = {})
  options = options.merge({
    headers:    @options[:headers].merge(options[:headers]    || {}),
    middleware: @options[:middleware] + (options[:middleware] || [])
  })

  self.class.new(@uri, @options.merge(options))
end