Class: Racket::Router

Inherits:
Object
  • Object
show all
Defined in:
lib/racket/router.rb

Overview

Handles routing in Racket applications.

Defined Under Namespace

Classes: Route

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter



40
41
42
43
44
# File 'lib/racket/router.rb', line 40

def initialize
  @router = HttpRouter.new
  @routes = {}
  @action_cache = Utils::Routing::ActionCache.new
end

Instance Attribute Details

#action_cacheObject (readonly)

Returns the value of attribute action_cache.



37
38
39
# File 'lib/racket/router.rb', line 37

def action_cache
  @action_cache
end

#routesObject (readonly)

Returns the value of attribute routes.



38
39
40
# File 'lib/racket/router.rb', line 38

def routes
  @routes
end

Instance Method Details

#get_route(controller_class, action, params) ⇒ String

Returns a route to the specified controller/action/parameter combination.



52
53
54
55
56
# File 'lib/racket/router.rb', line 52

def get_route(controller_class, action, params)
  fail "Cannot find controller #{controller_class}" unless @routes.key?(controller_class)
  params.flatten!
  Route.new(@routes[controller_class], action, params).to_s
end

#map(path, controller_class) ⇒ nil

Maps a controller to the specified path.



63
64
65
66
67
# File 'lib/racket/router.rb', line 63

def map(path, controller_class)
  map_controller(path.empty? ? '/' : path, controller_class)
  @router.add("#{path}(/*params)").to(controller_class)
  @action_cache.add(controller_class)
end

#render_error(status, error = nil) ⇒ Object

@todo: Allow the user to set custom handlers for different errors



70
71
72
73
74
75
76
# File 'lib/racket/router.rb', line 70

def render_error(status, error = nil)
  # If running in dev mode, let Rack::ShowExceptions handle the error.
  fail(error) if error && Application.dev_mode?

  # Not running in dev mode, let us handle the error ourselves.
  Response.generate_error_response(status)
end

#route(env) ⇒ Array

Routes a request and renders it.



82
83
84
85
86
87
88
89
90
# File 'lib/racket/router.rb', line 82

def route(env)
  catch :response do # Catches early exits from Controller.respond.
    # Ensure that that a controller will respond to the request. If not, send a 404.
    return render_error(404) unless (target_info = target_info(env))
    Utils.render_controller(env, target_info)
  end
rescue => err
  render_error(500, err)
end