Sha256: 5d29ab5a8f6cb2bb5bac1aa8fa588b40bc62614ac61116b2e9d330231addcef9

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

module APIClientBase
  module Request

    def self.module(opts={})
      mod = Module.new do
        mattr_accessor :api_client_base_request_options

        def self.included(base)
          base.class_attribute :api_client_base_request_options
          base.api_client_base_request_options =
            self.api_client_base_request_options
          base.send :include, APIClientBase::Request
        end
      end

      mod.api_client_base_request_options = opts

      mod
    end

    extend ActiveSupport::Concern

    included do
      include Virtus.model
      attribute :host, String
      attribute :uri, String, lazy: true, default: :default_uri
      attribute :action, Symbol, default: :default_action
      attribute(:api_client_base_path, String, {
        lazy: true,
        default: :default_api_client_base_path,
      })
    end

    def call
      require "typhoeus"
      if defined?(Typhoeus)
        request = Typhoeus::Request.new(
          uri,
          method: action,
          headers: headers,
          body: body,
          params: params,
        )

        request.run
      else
        fail "Either override #call or make sure Typhoeus is available for use."
      end
    end

    private

    def headers ; {}  ; end
    def body    ; nil ; end
    def params  ; {}  ; end

    def default_action
      self.class.api_client_base_request_options[:action] || :get
    end

    def default_uri
      uri = URI(host)
      uri.path = api_client_base_path if !api_client_base_path.nil?
      uri.to_s
    end

    def default_api_client_base_path
      return if !respond_to?(:path, true)
      path.scan(/:\w+/).reduce(path) do |new_path, var|
        attribute_name = var.gsub(":", "")
        value = CGI::escape(self.send(attribute_name).to_s)
        new_path.gsub(var, value.to_s)
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
api_client_base-1.3.0 lib/api_client_base/request.rb