Sha256: 3cebc412175488518b67142717a8ec5524fc94345abf587f5c2df65b20ee2ea8

Contents?: true

Size: 1.84 KB

Versions: 5

Compression:

Stored size: 1.84 KB

Contents

require 'socket'
require 'faraday'
require 'faraday_middleware'

require 'frenetic/version'
require 'frenetic/concerns/configurable'
require 'frenetic/concerns/briefly_memoizable'
require 'frenetic/middleware/hal_json'
require 'frenetic/resource'
require 'frenetic/resource_collection'

class Frenetic
  extend Forwardable
  include Configurable
  include BrieflyMemoizable

  def_delegators :connection, :get, :put, :post, :delete

  Error           = Class.new(StandardError)
  ConfigError     = Class.new(Error)
  ClientError     = Class.new(Error)
  ServerError     = Class.new(Error)
  ParsingError    = Class.new(Error)
  HypermediaError = Class.new(Error)

  def connection
    @connection ||= begin
      validate_configuration!

      Faraday.new( config ) do |builder|
        configure_authentication builder

        builder.response :hal_json

        configure_caching builder

        @builder_config.call( builder ) if @builder_config

        builder.adapter config.adapter
      end
    end
  end

  # Since Frenetic needs to frequently refer to the API design, the result of
  # this method is essentially cached, regardless of what caching middleware it
  # is configured with.
  #
  # It fully honors the HTTP Cache-Control headers that are returned by the API.
  #
  # If no Cache-Control header is returned, then the results are not memoized.
  def description
    if response = get( config.url.to_s ) and response.success?
      @description_age = cache_control_age( response.headers )

      response.body
    end
  end
  briefly_memoize :description

  def schema
    description['_embedded']['schema']
  end

private

  def cache_control_age( headers )
    if cache_age = headers['Cache-Control']
      age = cache_age.match(%r{max-age=(?<max_age>\d+)})[:max_age]

      Time.now + age.to_i
    else
      config.default_root_cache_age
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
frenetic-0.0.20.alpha.6 lib/frenetic.rb
frenetic-0.0.20.alpha.5 lib/frenetic.rb
frenetic-0.0.20.alpha.4 lib/frenetic.rb
frenetic-0.0.20.alpha.3 lib/frenetic.rb
frenetic-0.0.20.alpha.2 lib/frenetic.rb