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

Constant Summary collapse

ASSETS_REGEX =

Detect the most common assets.

/\.(css|png|jpe?g|gif|js|svg|ico|flv|mov|m4v|ogg|swf)\z/i.freeze
ACCEPT_REGEX =

Detect the ACCEPT header. IE8 send /.

%r{(text/html|\*/\*)}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(app, &block) ⇒ Middleware

Returns a new instance of Middleware.

Raises:

  • (ArgumentError)


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

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

  @app = app
  @block = block
end

Instance Method Details

#assets?(request) ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/browser/middleware.rb', line 66

def assets?(request)
  request.path.match(ASSETS_REGEX)
end

#call(env) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/browser/middleware.rb', line 22

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

  # Only apply verification on HTML requests.
  # This ensures that images, CSS and JavaScript
  # will be rendered.
  return run_app(env) unless process?(request)

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

  # No path, no match.
  return run_app(env) unless path

  resolve_redirection(env, request.path, path)
end

#html?(request) ⇒ Boolean

Returns:

  • (Boolean)


62
63
64
# File 'lib/browser/middleware.rb', line 62

def html?(request)
  request.env["HTTP_ACCEPT"].to_s.match(ACCEPT_REGEX)
end

#process?(request) ⇒ Boolean

Returns:

  • (Boolean)


58
59
60
# File 'lib/browser/middleware.rb', line 58

def process?(request)
  html?(request) && !assets?(request)
end

#redirect(path) ⇒ Object



50
51
52
# File 'lib/browser/middleware.rb', line 50

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

#resolve_redirection(env, current_path, path) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/browser/middleware.rb', line 40

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

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

#run_app(env) ⇒ Object



54
55
56
# File 'lib/browser/middleware.rb', line 54

def run_app(env)
  @app.call(env)
end