Sha256: da7d82a5a712c576f333ea339c934e249cc4d1b8590157d26c70d1092bb35d95

Contents?: true

Size: 1.83 KB

Versions: 5

Compression:

Stored size: 1.83 KB

Contents

module BooticClient
  module Strategies
    class Strategy

      attr_reader :options

      def initialize(config, client_opts = {}, &on_new_token)
        @config, @options, @on_new_token = config, client_opts, (on_new_token || Proc.new{})
        validate!
      end

      def root
        request_and_wrap :get, config.api_root, Entity
      end

      def from_hash(hash, wrapper_class = Entity)
        wrapper_class.new hash, self
      end

      def from_url(url, wrapper_class = Entity)
        request_and_wrap :get, url, wrapper_class
      end

      def request_and_wrap(request_method, href, wrapper_class, payload = {})
        pre_flight
        retryable do
          wrapper_class.new client.send(request_method, href, payload, request_headers).body, self
        end
      end

      def inspect
        %(#<#{self.class.name} root: #{config.api_root}>)
      end

      protected

      attr_reader :config, :on_new_token

      def validate!
        # Overwrite in sub classes
        # to raise ArgumentErrors on
        # missing config attributes of options values.
      end

      def pre_flight
        # Runs before every request
        # Overwrite in sub classes to run checks
        # (ie authorisation status, missing options, expired token refresh)
      end

      # Noop.
      # Overwrite in sub classes to implement retryable requests.
      # Example:
      #
      #   def retryable(&block)
      #      begin
      #        yield # issue request
      #      rescue SomeException => e
      #        fix_cause_of_exception
      #        yield # try again
      #      end
      #   end
      #
      def retryable(&block)
        yield
      end

      # Noop. Merge these headers into every request.
      def request_headers
        {}
      end

      def client
        @client ||= Client.new(options)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
bootic_client-0.0.21 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.20 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.19 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.18 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.17 lib/bootic_client/strategies/strategy.rb