Class: BokChoy::Request

Inherits:
Object
  • Object
show all
Defined in:
lib/bok_choy/request.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**args) ⇒ Request

Returns a new instance of Request.



14
15
16
17
18
19
20
# File 'lib/bok_choy/request.rb', line 14

def initialize(**args)
  @endpoint = args[:endpoint]
  @verbose = args[:verbose]
  @q = args[:q]
  @json = args[:json].to_json
  @options = args[:options] # TODO: not added at bok_choy.rb
end

Instance Attribute Details

#endpointObject

Returns the value of attribute endpoint.



8
9
10
# File 'lib/bok_choy/request.rb', line 8

def endpoint
  @endpoint
end

#optionsObject

Returns the value of attribute options.



12
13
14
# File 'lib/bok_choy/request.rb', line 12

def options
  @options
end

#qObject

Returns the value of attribute q.



9
10
11
# File 'lib/bok_choy/request.rb', line 9

def q
  @q
end

#verboseObject

Returns the value of attribute verbose.



10
11
12
# File 'lib/bok_choy/request.rb', line 10

def verbose
  @verbose
end

Instance Method Details

#performObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/bok_choy/request.rb', line 22

def perform

  args = {
    json: @json
  }
  opts = args.delete_if { |_k, v| v.nil? }

  Faraday::Utils.default_space_encoding = "+"

  conn = if verbose
           Faraday.new(url: BokChoy.base_url) do |f|
             f.response :logger
             f.use Faraday::BokChoyErrors::Middleware
             f.adapter Faraday.default_adapter
           end
         else
           Faraday.new(url: BokChoy.base_url) do |f|
             f.use Faraday::BokChoyErrors::Middleware
             f.adapter Faraday.default_adapter
           end
         end

  conn.headers['Accept'] = 'application/json,*/*'
  conn.headers[:user_agent] = make_user_agent
  conn.headers["X-USER-AGENT"] = make_user_agent
  conn.headers['Content-Type'] = 'application/json'

  if %w[name_refs].include? endpoint
    res = conn.post(endpoint, opts[:json])
  else
    res = conn.get(endpoint, opts)
  end

  # Handles endpoints that do not return JSON
  begin
    MultiJson.load(res.body)
  rescue MultiJson::ParseError
    res.body
  end
  
end