Class: Purple::Path

Inherits:
Object
  • Object
show all
Defined in:
lib/purple/path.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object



21
22
23
24
25
26
27
# File 'lib/purple/path.rb', line 21

def method_missing(method_name, *args, &)
  if children.any? { |child| child.name == method_name }
    children.find { |child| child.name == method_name }
  else
    super
  end
end

Instance Method Details

#execute(params = {}, args = {}) ⇒ Object



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
70
71
72
73
74
75
# File 'lib/purple/path.rb', line 29

def execute(params = {}, args = {})
  headers = {
    'Accept' => 'application/json',
    'Content-Type' => 'application/json'
  }

  if client.authorization
    authorization = client.authorization[:data].call

    headers.deep_merge!(authorization) if client.authorization[:type].in?(i[bearer custom_headers])
    params.deep_merge!(authorization) if client.authorization[:type] == :custom_query
  end

  connection = Faraday.new(url: client.domain) do |conn|
    conn.headers = headers
  end

  url = "#{client.domain}/#{full_path}"
  response = case method
             when :get
               connection.get(url, params)
             when :post
               connection.post(url, params.to_json)
             end

  resp_structure = responses.find { |resp| resp.status_code == response.status }

  if resp_structure.nil?
    raise "#{client.domain}/#{full_path} returns #{response.status}, but it is not defined in the client"
  else
    object = if resp_structure.body.is_a?(Purple::Responses::Body)
               resp_structure.body.validate!(response.body, args)
             elsif resp_structure.body == :default
               response.body
             else
               {}
             end

    client.callback&.call(url, params, headers, JSON.parse(response.body))

    if block_given?
      yield(resp_structure.status, object)
    else
      object
    end
  end
end

#full_pathObject



17
18
19
# File 'lib/purple/path.rb', line 17

def full_path
  parent.nil? ? name : "#{parent.full_path}/#{name}"
end