Class: Browser::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/browser/middleware.rb,
lib/browser/middleware/context.rb,
lib/browser/middleware/context/additions.rb,
lib/browser/middleware/context/url_methods.rb

Defined Under Namespace

Classes: Context

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, &block) ⇒ Middleware

Returns a new instance of Middleware.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
# File 'lib/browser/middleware.rb', line 7

def initialize(app, &block)
  raise ArgumentError, "Browser::Middleware requires a block" unless block

  @app = app
  @block = block
end

Instance Attribute Details

#envObject (readonly)

Returns the value of attribute env.



5
6
7
# File 'lib/browser/middleware.rb', line 5

def env
  @env
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
# File 'lib/browser/middleware.rb', line 14

def call(env)
  @env = env
  request = Rack::Request.new(env)

  path = catch(:redirected) do
    Context.new(request).instance_eval(&@block)
  end

  path ? resolve_redirection(request.path, path) : run_app!
end

#redirect(path) ⇒ Object



35
36
37
# File 'lib/browser/middleware.rb', line 35

def redirect(path)
  [301, {"Content-Type" => "text/html", "Location" => path}, []]
end

#resolve_redirection(current_path, path) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/browser/middleware.rb', line 25

def resolve_redirection(current_path, path)
  uri = URI.parse(path)

  if uri.path == current_path
    run_app!
  else
    redirect(path)
  end
end

#run_app!Object



39
40
41
# File 'lib/browser/middleware.rb', line 39

def run_app!
  @app.call(env)
end