Class: Apis::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/apis/builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, &block) ⇒ Builder

Returns a new instance of Builder.



4
5
6
7
8
9
10
11
# File 'lib/apis/builder.rb', line 4

def initialize(options = {}, &block)
  options.each do |key, value|
    send("#{key}=", value) if respond_to?("#{key}=")
  end
  @stack = []
  @mapping = {}
  block_eval(&block) if block
end

Instance Attribute Details

#lookup_contextObject

Returns the value of attribute lookup_context.



3
4
5
# File 'lib/apis/builder.rb', line 3

def lookup_context
  @lookup_context
end

Instance Method Details

#block_eval(&block) ⇒ Object



66
67
68
# File 'lib/apis/builder.rb', line 66

def block_eval(&block)
  instance_eval(&block)
end

#include?(middleware) ⇒ Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/apis/builder.rb', line 48

def include?(middleware)
  !!index(middleware)
end

#index(middleware) ⇒ Object



39
40
41
42
# File 'lib/apis/builder.rb', line 39

def index(middleware)
  middleware = lookup_middleware(middleware)
  @mapping[middleware]
end

#insert(middleware, index = nil) ⇒ Object



24
25
26
27
28
29
30
31
32
# File 'lib/apis/builder.rb', line 24

def insert(middleware, index = nil)
  middleware = lookup_middleware(middleware)
  raise Apis::DuplicateMiddleware, "#{middleware} already in stack" if include?(middleware)
  index ||= @stack.length
  @stack[index] = lambda do |parent|
    middleware.new(parent)
  end
  @mapping[middleware] = index
end

#lengthObject



44
45
46
# File 'lib/apis/builder.rb', line 44

def length
  @stack.length
end

#lookup_middleware(middleware) ⇒ Object



70
71
72
73
74
# File 'lib/apis/builder.rb', line 70

def lookup_middleware(middleware)
  @lookup_context && !(Class === middleware) ?
    @lookup_context.lookup(middleware) :
    middleware
end

#remove(middleware) ⇒ Object



34
35
36
37
# File 'lib/apis/builder.rb', line 34

def remove(middleware)
  middleware = lookup_middleware(middleware)
  @stack.delete_at(@mapping.delete(middleware))
end

#replace(old, middleware) ⇒ Object



17
18
19
20
21
22
# File 'lib/apis/builder.rb', line 17

def replace(old, middleware)
  if index = index(old)
    insert(middleware, index)
    remove(old)
  end
end

#to_aObject



52
53
54
# File 'lib/apis/builder.rb', line 52

def to_a
  @mapping.to_a.sort { |a, b| a.last <=> b.last}.map { |e| e.first }
end

#to_appObject



57
58
59
60
61
62
63
64
# File 'lib/apis/builder.rb', line 57

def to_app
  unless @stack.empty?
    inner_app = @stack.last.call(nil)
    @stack.reverse[1..-1].inject(inner_app) { |parent, lazy| lazy.call(parent) }
  else
    []
  end
end

#use(middleware) ⇒ Object



13
14
15
# File 'lib/apis/builder.rb', line 13

def use(middleware)
  insert(middleware)
end