Sha256: 940c78a87b2c17830f5e4c5f1e52b9d8984cb5ac6860a3f826339b8b6bd54aad

Contents?: true

Size: 1.63 KB

Versions: 3

Compression:

Stored size: 1.63 KB

Contents

require 'patron'
require 'addressable/uri'
require 'faraday'
require 'faraday_middleware'
require 'rack-cache'

require "frenetic/configuration"
require "frenetic/hal_json"
require "frenetic/resource"
require "frenetic/version"

class Frenetic
  Error                 = Class.new(StandardError)
  ConfigurationError    = Class.new(Error)
  MissingAPIReference   = Class.new(Error)
  InvalidAPIDescription = Class.new(Error)

  extend Forwardable
  def_delegators :@connection, :get, :put, :post, :delete

  attr_reader  :connection
  alias_method :conn, :connection

  def initialize( config = {} )
    config      = Configuration.new( config )

    yield config if block_given?

    api_url     = Addressable::URI.parse( config.url )
    @root_url   = api_url.path

    @connection = Faraday.new( config.to_hash ) do |builder|
      builder.use HalJson

      config.middleware.each { |mw| builder.use(*mw) }

      builder.request :basic_auth, config.username, config.password

      builder.response :logger if config.response[:use_logger]

      if config.cache.present?
        builder.use FaradayMiddleware::RackCompatible, Rack::Cache::Context, config.cache
      end

      builder.adapter :patron
    end
  end

  def description
    @description ||= load_description
  end

  # A naive approach to reloading a Frenetic instance for testing purpose.
  def reload!
    instance_variables.each { |var| instance_variable_set(var, nil) }
  end

private

  def load_description
    if response = get( @root_url ) and response.success?
      response.body
    else
      raise InvalidAPIDescription, "Status code #{response.status} encountered."
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
frenetic-0.0.9 lib/frenetic.rb
frenetic-0.0.8 lib/frenetic.rb
frenetic-0.0.7 lib/frenetic.rb