Class: Startback::Context::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/startback/context/middleware.rb

Overview

Rack middleware that installs a particular context instance on the Rack environment.

Examples:

# Use the default context class
Rack::Builder.new do
  use Startback::Context::Middleware

  run ->(env){
    ctx = env[Startback::Context::Middleware::RACK_ENV_KEY]
    ctx.is_a?(Startback::Context) # => true
  }
end

# Use a user defined context class
Rack::Builder.new do
  use Startback::Context::Middleware, MyContextClass.new

  run ->(env){
    ctx = env[Startback::Context::Middleware::RACK_ENV_KEY]
    ctx.is_a?(MyContextClass)     # => true (your subclass)
    ctx.is_a?(Startback::Context) # => true (required!)
  }
end

Constant Summary collapse

RACK_ENV_KEY =
'SAMBACK_CONTEXT'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, context = Context.new) ⇒ Middleware

Returns a new instance of Middleware.



34
35
36
37
# File 'lib/startback/context/middleware.rb', line 34

def initialize(app, context = Context.new)
  @app = app
  @context = context
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



38
39
40
# File 'lib/startback/context/middleware.rb', line 38

def context
  @context
end

Class Method Details

.context(env) ⇒ Object



47
48
49
# File 'lib/startback/context/middleware.rb', line 47

def self.context(env)
  env[RACK_ENV_KEY]
end

Instance Method Details

#call(env) ⇒ Object



40
41
42
43
44
45
# File 'lib/startback/context/middleware.rb', line 40

def call(env)
  env[RACK_ENV_KEY] ||= context.dup.tap{|c|
    c.original_rack_env = env.dup
  }
  @app.call(env)
end