module MangoPay

We can use MultiJson directly , why do we even have this module ?

Constants

VERSION

Public Class Methods

api_path() click to toggle source
# File lib/mangopay.rb, line 73
def api_path
  "/#{version_code}/#{MangoPay.configuration.client_id}"
end
api_uri(url='') click to toggle source
# File lib/mangopay.rb, line 77
def api_uri(url='')
  URI(configuration.root_url + url)
end
configuration() click to toggle source
# File lib/mangopay.rb, line 86
def configuration
  config = Thread.current[:mangopay_configuration]

  config                                                ||
  ( @last_configuration_set &&
    (self.configuration = @last_configuration_set.dup)) ||
  (self.configuration = MangoPay::Configuration.new)
end
configuration=(value) click to toggle source
# File lib/mangopay.rb, line 81
def configuration=(value)
  Thread.current[:mangopay_configuration] = value
  @last_configuration_set = value
end
configure() { |config| ... } click to toggle source
# File lib/mangopay.rb, line 95
def configure
  config = self.configuration
  yield config
  self.configuration = config
end
fetch_response(idempotency_key) click to toggle source

Retrieve a previous response by idempotency_key See docs.mangopay.com/api-references/idempotency-support/

# File lib/mangopay.rb, line 172
def fetch_response(idempotency_key)
  url = "#{api_path}/responses/#{idempotency_key}"
  request(:get, url)
end
ratelimit() click to toggle source
# File lib/mangopay.rb, line 109
def ratelimit
  @ratelimit
end
ratelimit=(obj) click to toggle source
# File lib/mangopay.rb, line 113
def ratelimit=(obj)
  @ratelimit = obj
end
request(method, url, params={}, filters={}, headers_or_idempotency_key = nil, before_request_proc = nil) click to toggle source
  • method: HTTP method; lowercase symbol, e.g. :get, :post etc.

  • url: the part after Configuration#root_url

  • params: hash; entity data for creation, update etc.; will dump it by JSON and assign to Net::HTTPRequest#body

  • filters: hash; pagination params etc.; will encode it by URI and assign to URI#query

  • headers_or_idempotency_key: hash of headers; or replaced by request_headers if nil; or added to request_headers as idempotency key otherwise (see docs.mangopay.com/api-references/idempotency-support/)

  • before_request_proc: optional proc; will call it passing the Net::HTTPRequest instance just before Net::HTTPRequest#request

Raises MangoPay::ResponseError if response code != 200.

# File lib/mangopay.rb, line 127
def request(method, url, params={}, filters={}, headers_or_idempotency_key = nil, before_request_proc = nil)
  uri = api_uri(url)
  uri.query = URI.encode_www_form(filters) unless filters.empty?

  if headers_or_idempotency_key.is_a?(Hash)
    headers = headers_or_idempotency_key
  else
    headers = request_headers
    headers['Idempotency-Key'] = headers_or_idempotency_key if headers_or_idempotency_key != nil
  end

  res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, :read_timeout => configuration.http_timeout, ssl_version: :TLSv1_2) do |http|
    req = Net::HTTP::const_get(method.capitalize).new(uri.request_uri, headers)
    req.body = JSON.dump(params)
    before_request_proc.call(req) if before_request_proc
    do_request(http, req, uri)
  end

  raise MangoPay::ResponseError.new(uri, '408', {'Message' => 'Request Timeout'}) if res.nil?

  # decode json data
  data = res.body.to_s.empty? ? {} : JSON.load(res.body.to_s)

  unless res.is_a?(Net::HTTPOK)
    raise MangoPay::ResponseError.new(uri, res.code, data)
  end

  # copy pagination info if any
  ['x-number-of-pages', 'x-number-of-items'].each { |k|
    filters[k.gsub('x-number-of-', 'total_')] = res[k].to_i if res[k]
  }

  if res['x-ratelimit']
    self.ratelimit = {
      limit: res['x-ratelimit'].split(", "),
      remaining: res['x-ratelimit-remaining'].split(", "),
      reset: res['x-ratelimit-reset'].split(", ")
    }
  end

  data
end
version_code() click to toggle source
# File lib/mangopay.rb, line 69
def version_code
  "v2.01"
end
with_configuration(config) { || ... } click to toggle source
# File lib/mangopay.rb, line 101
def with_configuration(config)
  original_config = MangoPay.configuration
  MangoPay.configuration = config
  yield
ensure
  MangoPay.configuration = original_config
end

Private Class Methods

do_request(http, req, uri) click to toggle source
# File lib/mangopay.rb, line 209
def do_request(http, req, uri)
  if logs_required?
    do_request_with_log(http, req, uri)
  else
    do_request_without_log(http, req)
  end
end
do_request_with_log(http, req, uri) click to toggle source
# File lib/mangopay.rb, line 217
def do_request_with_log(http, req, uri)
  res, time = nil, nil
  params = FilterParameters.request(req.body)
  line = "[#{Time.now.iso8601}] #{req.method.upcase} \"#{uri.to_s}\" #{params}"
  begin
    time = Benchmark.realtime {
      begin
        res = do_request_without_log(http, req)
      rescue Net::ReadTimeout
        res = nil
      end
    }
    res
  ensure
    line = "#{log_severity(res)} #{line}"
    if res.nil?
      params = ''
      line += "\n  [#{(time * 1000).round(1)}ms] 408 Request Timeout #{params}\n"
    else
      params = FilterParameters.response(res.body)
      line += "\n  [#{(time * 1000).round(1)}ms] #{res.code} #{params}\n"
    end
    logger.info { line }
  end
end
do_request_without_log(http, req) click to toggle source
# File lib/mangopay.rb, line 243
def do_request_without_log(http, req)
  http.request(req)
end
get_uname() click to toggle source
# File lib/mangopay.rb, line 189
def get_uname
  `uname -a 2>/dev/null`.strip if RUBY_PLATFORM =~ /linux|darwin/i
rescue Errno::ENOMEM
  'uname lookup failed'
end
log_severity(res) click to toggle source
# File lib/mangopay.rb, line 247
def log_severity(res)
  errors = [Net::HTTPClientError, Net::HTTPServerError, Net::HTTPUnknownResponse]
  errors.any? { |klass| res.is_a?(klass) } ? 'E' : 'I'
end
logger() click to toggle source
# File lib/mangopay.rb, line 252
def logger
  raise NotImplementedError unless logs_required?
  return @logger if @logger

  if !configuration.logger.nil?
    @logger = configuration.logger
  elsif !configuration.log_file.nil?
    @logger = Logger.new(configuration.log_file)
    @logger.formatter = proc do |_, _, _, msg|
      "#{msg}\n"
    end
  end

  @logger
end
logs_required?() click to toggle source
# File lib/mangopay.rb, line 268
def logs_required?
  !configuration.log_file.nil? || !configuration.logger.nil?
end
request_headers() click to toggle source
# File lib/mangopay.rb, line 195
def request_headers
  auth_token = AuthorizationToken::Manager.get_token
  headers = {
      'User-Agent' => "MangoPay V2 SDK Ruby Bindings #{VERSION}",
      'Authorization' => "#{auth_token['token_type']} #{auth_token['access_token']}",
      'Content-Type' => 'application/json'
  }
  begin
    headers.update('x_mangopay_client_user_agent' => JSON.dump(user_agent))
  rescue => e
    headers.update('x_mangopay_client_raw_user_agent' => user_agent.inspect, error: "#{e} (#{e.class})")
  end
end
user_agent() click to toggle source
# File lib/mangopay.rb, line 179
def user_agent
  {
      bindings_version: VERSION,
      lang: 'ruby',
      lang_version: "#{RUBY_VERSION} p#{RUBY_PATCHLEVEL} (#{RUBY_RELEASE_DATE})",
      platform: RUBY_PLATFORM,
      uname: get_uname
  }
end