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



16
17
18
19
20
21
22
23
24
# File 'lib/bok_choy/request.rb', line 16

def initialize(**args)
  @endpoint = args[:endpoint]
  @verbose = args[:verbose]
  @q = args[:q]
  @item_id = args[:item_id]
  @page_num = args[:page_num]
  @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

#item_idObject

Returns the value of attribute item_id.



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

def item_id
  @item_id
end

#optionsObject

Returns the value of attribute options.



14
15
16
# File 'lib/bok_choy/request.rb', line 14

def options
  @options
end

#page_numObject

Returns the value of attribute page_num.



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

def page_num
  @page_num
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



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
63
64
65
66
67
68
69
# File 'lib/bok_choy/request.rb', line 26

def perform

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

  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