Sha256: 2028270e1e6a5d4f6a75f1404dc358c1776eec7c9342a076f750ae2a500632dc

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

require 'fattr'
require 'forwardable'
require 'leadlight/request'

module Leadlight
  module Service
    extend Forwardable

    attr_reader :service_options
    fattr(:logger)  { service_options.fetch(:logger) { ::Logger.new($stderr) } }
    fattr(:tints)   { self.class.tints }
    fattr(:codec) { service_options.fetch(:codec) { Codec.new } }

    def_delegators :codec, :encode, :decode
    def_delegators 'self.class', :types, :type_for_name

    def initialize(service_options={})
      @service_options = service_options
    end

    def root
      get('/') do |r|
        return r
      end
    end

    def url
      self.class.url
    end

    def connection
      @connection ||= Faraday.new(url: self.url) do |builder|
        builder.use Leadlight::ServiceMiddleware, service: self
        instance_exec(builder, &connection_stack)
        builder.use Faraday::Response::Logger, logger
        instance_exec(builder, &Leadlight.common_connection_stack)
      end
    end

    [:options, :head, :get, :post, :put, :delete, :patch].each do |name|
      define_method(name) do |url, *args, &block|
        perform_request(url, name, *args, &block)
      end
    end

    # Convenience method for a quick GET which submits, waits, raises
    # on error, and yields the representation.
    def get_representation!(*args, &block)
      get(*args).raise_on_error.submit_and_wait(&block)
    end

    private

    def perform_request(url, http_method, params={}, body=nil, &representation_handler)
      req = Request.new(connection, url, http_method, params, body)
      req.on_prepare_request do |faraday_request|
        prepare_request(faraday_request)
      end
      if representation_handler
        req.submit_and_wait(&representation_handler)
      end
      req
    end

    def prepare_request(request)
      # Override in subclasses
    end

    def connection_stack
      self.class.connection_stack
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
leadlight-0.0.2 lib/leadlight/service.rb