Class: Grape::Middleware::Stack

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Enumerable
Defined in:
lib/grape/middleware/stack.rb

Overview

Class to handle the stack of middlewares based on ActionDispatch::MiddlewareStack It allows to insert and insert after

Defined Under Namespace

Classes: Middleware

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeStack

Returns a new instance of Stack.



50
51
52
53
# File 'lib/grape/middleware/stack.rb', line 50

def initialize
  @middlewares = []
  @others = []
end

Instance Attribute Details

#middlewaresObject

Returns the value of attribute middlewares.



46
47
48
# File 'lib/grape/middleware/stack.rb', line 46

def middlewares
  @middlewares
end

#othersObject

Returns the value of attribute others.



46
47
48
# File 'lib/grape/middleware/stack.rb', line 46

def others
  @others
end

Instance Method Details

#buildRack::Builder

Returns the builder object with our middlewares applied.

Returns:

  • (Rack::Builder)

    the builder object with our middlewares applied



84
85
86
87
88
89
90
91
# File 'lib/grape/middleware/stack.rb', line 84

def build
  Rack::Builder.new.tap do |builder|
    others.shift(others.size).each { |m| merge_with(m) }
    middlewares.each do |m|
      m.build(builder)
    end
  end
end

#concat(other_specs) ⇒ Object

Parameters:

  • other_specs (Array)

    An array of middleware specifications (e.g. [[:use, klass], [:insert_before, *args]])



95
96
97
98
99
# File 'lib/grape/middleware/stack.rb', line 95

def concat(other_specs)
  use, not_use = other_specs.partition { |o| o.first == :use }
  others << not_use
  merge_with(use)
end

#insert(index, klass, *args, &block) ⇒ Object Also known as: insert_before



55
56
57
58
# File 'lib/grape/middleware/stack.rb', line 55

def insert(index, klass, *args, &block)
  index = assert_index(index, :before)
  middlewares.insert(index, self.class::Middleware.new(klass, args, block))
end

#insert_after(index, *args, &block) ⇒ Object



62
63
64
65
# File 'lib/grape/middleware/stack.rb', line 62

def insert_after(index, *args, &block)
  index = assert_index(index, :after)
  insert(index + 1, *args, &block)
end

#merge_with(middleware_specs) ⇒ Object



72
73
74
75
76
77
78
79
80
81
# File 'lib/grape/middleware/stack.rb', line 72

def merge_with(middleware_specs)
  middleware_specs.each do |operation, klass, *args|
    if args.last.is_a?(Proc)
      last_proc = args.pop
      public_send(operation, klass, *args, &last_proc)
    else
      public_send(operation, klass, *args)
    end
  end
end

#use(klass, *args, &block) ⇒ Object



67
68
69
70
# File 'lib/grape/middleware/stack.rb', line 67

def use(klass, *args, &block)
  middleware = self.class::Middleware.new(klass, args, block)
  middlewares.push(middleware)
end