Module: Likeno::RequestMethods

Included in:
Entity
Defined in:
lib/likeno/request_methods.rb

Instance Method Summary collapse

Instance Method Details

#addressObject

Raises:

  • (NotImplementedError)


43
44
45
# File 'lib/likeno/request_methods.rb', line 43

def address
  raise NotImplementedError
end

#clientObject

TODO: probably the connection could be a class static variable.



48
49
50
51
52
53
54
# File 'lib/likeno/request_methods.rb', line 48

def client
  Faraday.new(url: address) do |conn|
    conn.request :json
    conn.response :json, content_type: /\bjson$/
    conn.adapter Faraday.default_adapter # make requests with Net::HTTP
  end
end

#endpointObject



56
57
58
# File 'lib/likeno/request_methods.rb', line 56

def endpoint
  entity_name.pluralize
end

#entity_nameObject



64
65
66
67
68
69
70
71
72
# File 'lib/likeno/request_methods.rb', line 64

def entity_name
  # This loop is a generic way to make this work even when the children class has a different name
  entity_class = self
  until entity_class.name.include?("#{module_name}::")
    entity_class = entity_class.superclass
  end

  entity_class.name.split('::').last.underscore.downcase
end

#module_nameObject

Raises:

  • (NotImplementedError)


60
61
62
# File 'lib/likeno/request_methods.rb', line 60

def module_name
  raise NotImplementedError
end

#request(action, params = {}, method = :post, prefix = '', headers = {}) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/likeno/request_methods.rb', line 22

def request(action, params = {}, method = :post, prefix = '', headers = {})
  response = client.send(method) do |request|
    url = "/#{endpoint}/#{action}".gsub(':id', params[:id].to_s)
    url = "/#{prefix}#{url}" unless prefix.empty?
    request.url url
    request.body = params unless method == :get || params.empty?
    request.options.timeout = 300
    request.options.open_timeout = 300

    headers.each { |(key, value)| request.headers[key] = value }
  end

  if response.success?
    response.body
  elsif response.status == 404
    raise Likeno::Errors::RecordNotFound.new(response: response)
  else
    raise Likeno::Errors::RequestError.new(response: response)
  end
end