Sha256: 112fa46fc3ad39b3e45e3b34016e5a74543f568d6a9804f4afc3b88571f25ab3

Contents?: true

Size: 1.73 KB

Versions: 9

Compression:

Stored size: 1.73 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 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

9 entries across 9 versions & 1 rubygems

Version Path
bootic_client-0.0.16 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.15 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.14 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.13 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.12 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.11 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.10 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.9 lib/bootic_client/strategies/strategy.rb
bootic_client-0.0.8 lib/bootic_client/strategies/strategy.rb