module Locomotive::Coal::Resources::Concerns

Private Instance Methods

_connection() click to toggle source
# File lib/locomotive/coal/resources/concerns/request.rb, line 94
def _connection
  @_connection ||= Faraday.new(url: "#{uri.scheme}://#{uri.host}:#{uri.port}") do |faraday|
    faraday.request     :multipart
    faraday.request     :url_encoded             # form-encode POST params
    faraday.basic_auth  *uri.userinfo.split(':') if uri.userinfo

    faraday.use         FaradayMiddleware::ParseJson, content_type: /\bjson$/

    # ENV['no_proxy'] ignored in Faraday.default_adapter (Net::HTTP)
    faraday.adapter :httpclient
  end
end
_do_request(action, endpoint, parameters) click to toggle source
# File lib/locomotive/coal/resources/concerns/request.rb, line 67
def _do_request(action, endpoint, parameters)
  # compatibility with v2.5.x
  parameters = parameters.merge(auth_token: credentials[:token]) if _token

  _connection.send(action, endpoint) do |request|
    request.headers.merge!(_request_headers(parameters))

    if %i(post put).include?(action)
      request.body = _encode_parameters(parameters)
    else
      request.params = parameters
    end
  end
end
_encode_parameters(parameters) click to toggle source

github.com/ruby-grape/grape/issues/1028

# File lib/locomotive/coal/resources/concerns/request.rb, line 118
def _encode_parameters(parameters)
  return parameters unless parameters.is_a?(Hash)
  parameters.tap do
    parameters.each do |key, value|
      if value.is_a?(Array)
        parameters[key] = encode_array_to_hash(value) if value.first.is_a?(Hash)
      elsif value.is_a?(Hash)
        parameters[key] = _encode_parameters(value)
      end
    end
  end
end
_request_headers(parameters) click to toggle source
# File lib/locomotive/coal/resources/concerns/request.rb, line 82
def _request_headers(parameters)
  { 'Accept' => 'application/json' }.tap do |headers|
    if _token
      headers['X-Locomotive-Account-Email'] = credentials[:email]
      headers['X-Locomotive-Account-Token'] = credentials[:token]
      headers['X-Locomotive-Site-Handle']   = credentials[:handle] if credentials[:handle].present?
    end

    headers['X-Locomotive-Locale'] = parameters.delete(:_locale).to_s if parameters.try(:has_key?, :_locale)
  end
end
_token() click to toggle source
# File lib/locomotive/coal/resources/concerns/request.rb, line 107
def _token
  return if !!@without_token

  if credentials[:token].respond_to?(:call)
    credentials[:token] = credentials[:token].call
  end

  credentials[:token]
end
encode_array_to_hash(value) click to toggle source
{ name: 'a' }, { name: 'b' }

> { 0 => { name: 'a' }, 1 => { name: 'b' } }

# File lib/locomotive/coal/resources/concerns/request.rb, line 132
def encode_array_to_hash(value)
  {}.tap do |hash|
    value.each_with_index do |v, index|
      hash[index] = _encode_parameters(v)
    end
  end
end