Class: Charming::Router

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

Overview

Router manages an application’s route table and provides a Rails-inspired DSL for defining routes. Each route maps a URL path to a controller, action (implicitly :show), and title (for sidebar display).

Defined Under Namespace

Classes: DynamicRoute, Route

Instance Method Summary collapse

Constructor Details

#initialize(namespace: nil) ⇒ Router

Initializes a new router with an optional namespace prefix for controller constant lookups.



25
26
27
28
29
# File 'lib/charming/router.rb', line 25

def initialize(namespace: nil)
  @namespace = namespace
  @routes = {}
  @dynamic_routes = []
end

Instance Method Details

#allObject

Returns all registered routes as Route objects, ordered by insertion. Consumed by the application loop to populate the sidebar and by controllers for navigation context.



68
69
70
# File 'lib/charming/router.rb', line 68

def all
  @routes.values
end

#drawObject

Evaluates a block in the context of this Router instance using instance_eval, allowing DSL calls like screen and root to register routes. This is how ‘routes.draw { screen “/”, to: “HomeController”, title: “Home” }` works.



33
34
35
# File 'lib/charming/router.rb', line 33

def draw(&)
  instance_eval(&)
end

#resolve(path = "/") ⇒ Object

Resolves a route by path from the router’s table. Exact routes win over dynamic routes. Raises KeyError if no route matches. Used at runtime to look up the controller class and action for incoming requests.



62
63
64
# File 'lib/charming/router.rb', line 62

def resolve(path = "/")
  @routes[path] || resolve_dynamic(path) || raise(KeyError, "key not found: #{path.inspect}")
end

#root(target, title: "Home") ⇒ Object

Registers the home screen at “/” with a given title. Shorthand for ‘screen path, to: target`. Example: `root “HomeController”` maps `/` → HomeController#show with title “Home”.



39
40
41
# File 'lib/charming/router.rb', line 39

def root(target, title: "Home")
  screen("/", to: target, title: title)
end

#screen(path, to:, title: nil) ⇒ Object

Maps a URL path to a controller and action (e.g. “HomeController” for HomeController#show). Builds a Route object from the path, resolved controller constant, parsed action, and an optional or derived title.



45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/charming/router.rb', line 45

def screen(path, to:, title: nil)
  controller_name, action = to.split("#", 2)
  route = Route.new(
    path: path,
    controller_class: constantize(controller_constant_name(controller_name)),
    action: action.to_sym,
    title: title || derive_title(path),
    params: {}
  )
  @routes[path] = route
  @dynamic_routes.reject! { |dynamic_route| dynamic_route.route.path == path }
  @dynamic_routes << compile_dynamic_route(route) if dynamic_path?(path)
end