Class: Commute::Api

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Singleton
Defined in:
lib/commute/api.rb

Overview

An Api holds:

* Contexts of defaults.
* Named contexts (= Api calls)

Every Api is a singleton, it contains no state, only some name configurations (contexts).

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeApi

Initializes an Api with a parallel manager.



34
35
36
37
# File 'lib/commute/api.rb', line 34

def initialize
  @queue = []
  @hydra = ::Typhoeus::Hydra.new
end

Instance Attribute Details

#queueObject

Returns the value of attribute queue.



20
21
22
# File 'lib/commute/api.rb', line 20

def queue
  @queue
end

Class Method Details

.method_missing(name, *args, &block) ⇒ Object

Call missing methods on the default context.



28
29
30
# File 'lib/commute/api.rb', line 28

def method_missing name, *args, &block
  default.send name, *args, &block
end

Instance Method Details

#commute(request) ⇒ Object

Queue a request for later parallel execution.

Parameters:

  • request (Typhoeus::Request)

    The request to queue.



65
66
67
# File 'lib/commute/api.rb', line 65

def commute request
  @queue << request
end

#defaultContext

A pretty standard starting point is the ‘default` context. An Api class can implement it to provide some default options and stack layers.

Returns:



43
44
45
# File 'lib/commute/api.rb', line 43

def default
  @default ||= raw
end

#rawContext

Get a raw context without any defaults.

Returns:

  • (Context)

    A raw context for this api.



50
51
52
# File 'lib/commute/api.rb', line 50

def raw
  @raw ||= Context.new self, {}, Stack.new
end

#rush(request = nil) ⇒ Object

Executes all requests in the queue in parallel.

Parameters:

  • request (Typhoeus::Request) (defaults to: nil)

    Last request to add to the queue. Shortcut to commute and rush one request in one line.



73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/commute/api.rb', line 73

def rush request = nil
  commute request if request
  # Authorize each request right before executing
  @queue.each do |request|
    request.headers['Authorization'] = authorize(request.context) if respond_to? :authorize
    @hydra.queue request
  end
  # Clear the queue.
  @queue.clear
  # Run all requests.
  @hydra.run
end

#with(options = {}, &stack_mod) ⇒ Context

Start scoping on this Api. Creates a context with provided options and stack.

Returns:

  • (Context)

    The created context.



58
59
60
# File 'lib/commute/api.rb', line 58

def with options = {}, &stack_mod
  default.with options, &stack_mod
end