Sha256: a3788b17b1edd6be9555cb90c05eaf044013cc9a931c0041a5d1b5f8d12c66a4

Contents?: true

Size: 1.71 KB

Versions: 1

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

require 'hphones/version'
require 'hphones/endpoint'
require 'hphones/request'
require 'hphones/response'

require 'faraday'

##
# Base class for Hphones. Contains API data and acts as a central place to call methods on.
#
class Hphones
  # The root path of the Headphones API.
  ROOT_PATH = 'api'

  attr_reader :api_key

  # @param host [String] the hostname of the Headphones server
  # @param port [String, Integer] the port of the Headphones server
  # @param api_key [String] the API key generated by Headphones
  # @param protocol [String] the protocol being used (usually 'http' or 'https')
  # @param http_root [String] the optional root path set in Headphones
  def initialize(host:, port:, api_key:, protocol: 'http', http_root: nil)
    @host = host
    @port = port
    @protocol = protocol
    @http_root = decorate_http_root(http_root)

    @api_key = api_key
  end

  # Connection and URL stuff

  def connection
    @connection ||= Faraday.new(url: url)
  end

  def url
    @url ||= "#{protocol}://#{host}:#{port}"
  end

  def base_path
    @base_path ||= "#{http_root}/#{ROOT_PATH}"
  end

  # Methods to pass to Endpoint

  def method_missing(mth, *args, &blk)
    return fetch_from_endpoint(mth, *args) if lookup_endpoint(mth)

    super
  end

  def respond_to_missing?(mth, *)
    !!lookup_endpoint(mth) || super
  end

  private

  attr_reader :host, :port, :protocol, :http_root

  def lookup_endpoint(endpoint)
    Endpoint.lookup endpoint
  end

  def fetch_from_endpoint(endpoint, params = {})
    Endpoint.new(endpoint, self, params).fetch
  end

  def decorate_http_root(http_root)
    if http_root =~ %r{^\/} || http_root.nil?
      http_root
    else
      "/#{http_root}"
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hphones-ruby-0.0.2 lib/hphones.rb