File: router.rb

package info (click to toggle)
ruby-blade 0.7.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 208 kB
  • sloc: ruby: 819; makefile: 3; sh: 3
file content (36 lines) | stat: -rw-r--r-- 798 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module Blade::RackRouter
  extend ActiveSupport::Concern

  DEFAULT = :*

  included do
    cattr_accessor(:routes) { Hash.new }
  end

  class_methods do
    def route(path, action)
      pattern = /^\/?#{path.gsub(/\*/, ".*")}$/
      base_path = path.match(/([^\*]*)\*?/)[1]
      routes[path] = { action: action, pattern: pattern, base_path: base_path }
      self.routes = routes.sort_by { |path, value| -path.size }.to_h
      routes[path]
    end

    def default_route(action)
      routes[DEFAULT] = { action: action }
    end

    def find_route(path)
      if route = routes.detect { |key, details| path =~ details[:pattern] }
        route[1]
      else
        routes[DEFAULT]
      end
    end
  end

  private
    def find_route(*args)
      self.class.find_route(*args)
    end
end