Class: Rack::Multiplexer

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/multiplexer.rb,
lib/rack/multiplexer/version.rb

Defined Under Namespace

Classes: Route

Constant Summary collapse

DEFAULT_NOT_FOUND_APPLICATION =
->(env) {
  [
    404,
    {
      "Content-Type" => "text/plain",
      "Content-Length" => "0",
    },
    [""],
  ]
}
VERSION =
"0.0.2"

Instance Method Summary collapse

Constructor Details

#initialize(not_found_application = DEFAULT_NOT_FOUND_APPLICATION, &block) ⇒ Multiplexer

Returns a new instance of Multiplexer.



17
18
19
20
# File 'lib/rack/multiplexer.rb', line 17

def initialize(not_found_application = DEFAULT_NOT_FOUND_APPLICATION, &block)
  @not_found_application = not_found_application
  instance_eval(&block) if block
end

Instance Method Details

#any(pattern, application, &block) ⇒ Object



47
48
49
# File 'lib/rack/multiplexer.rb', line 47

def any(pattern, application, &block)
  append("ANY", pattern, application || block)
end

#append(method, pattern, application) ⇒ Object



51
52
53
# File 'lib/rack/multiplexer.rb', line 51

def append(method, pattern, application)
  routes[method] << Route.new(pattern, application)
end

#call(env) ⇒ Object



22
23
24
25
26
27
28
29
# File 'lib/rack/multiplexer.rb', line 22

def call(env)
  path = env["PATH_INFO"]
  (
    routes[env["REQUEST_METHOD"]].find {|route| route.match?(path) } ||
    routes["ANY"].find {|route| route.match?(path) } ||
    @not_found_application
  ).call(env)
end

#default_not_found_applicationObject



60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/rack/multiplexer.rb', line 60

def default_not_found_application
  ->(env) {
    [
      404,
      {
        "Content-Type" => "text/plain",
        "Content-Length" => 0,
      },
      [""],
    ]
  }
end

#delete(pattern, application = nil, &block) ⇒ Object



43
44
45
# File 'lib/rack/multiplexer.rb', line 43

def delete(pattern, application = nil, &block)
  append("DELETE", pattern, application || block)
end

#get(pattern, application = nil, &block) ⇒ Object



31
32
33
# File 'lib/rack/multiplexer.rb', line 31

def get(pattern, application = nil, &block)
  append("GET", pattern, application || block)
end

#post(pattern, application = nil, &block) ⇒ Object



35
36
37
# File 'lib/rack/multiplexer.rb', line 35

def post(pattern, application = nil, &block)
  append("POST", pattern, application || block)
end

#put(pattern, application = nil, &block) ⇒ Object



39
40
41
# File 'lib/rack/multiplexer.rb', line 39

def put(pattern, application = nil, &block)
  append("PUT", pattern, application || block)
end

#routesObject



56
57
58
# File 'lib/rack/multiplexer.rb', line 56

def routes
  @routes ||= Hash.new {|hash, key| hash[key] = [] }
end