Class: Wings::Route

Inherits:
Object show all
Defined in:
lib/wings/routing.rb

Instance Method Summary collapse

Constructor Details

#initializeRoute

Returns a new instance of Route.



3
4
5
# File 'lib/wings/routing.rb', line 3

def initialize
  @rules = []
end

Instance Method Details

#check_url(url, req_method) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/wings/routing.rb', line 72

def check_url(url, req_method)
  (@rules + default_matches).each do |r|
    m      = r[:regex].match(url)
    params = r[:options].dup

    next unless m
    next unless req_method == params[:verb].to_s

    if vars = r[:vars]
      vars.each_with_index do |v, i|
        params[v] = m.captures[i]
      end
    end

    dest = params[:to] || "#{params['controller']}##{params['action']}"
    return get_destination(dest, params)
  end

  nil
end

#match(url, **opts) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/wings/routing.rb', line 45

def match(url, **opts)
  vars  = []
  regex = url.split('/')
            .reject { |pt| pt.empty? }
            .map do |part|
    if part[0] == ':'
      vars << part[1..-1]
      '([a-zA-Z0-9]+)'
    elsif part[0] == '*'
      vars << part[1..-1]
      '(.*)'
    else
      part
    end
  end.join('/')

  opts[:verb] ||= :GET

  @rules.push(
    {
      regex:   Regexp.new("^/#{regex}/?$"),
      options: opts,
      vars:    vars,
    }
  )
end

#resources(obj, **options) ⇒ Object

actions: ‘index`, `new`, `create`, `show`, `edit`, `update`, `destroy`



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/wings/routing.rb', line 17

def resources(obj, **options)
  actions = {
    index:   { path: "#{obj}" },
    new:     { path: "#{obj}/new" },
    create:  { path: "#{obj}", verb: :POST },
    show:    { path: "#{obj}/:id" },
    edit:    { path: "#{obj}/:id/edit" },
    update:  { path: "#{obj}/:id", verb: :PATCH },
    destroy: { path: "#{obj}/:id", verb: :DELETE },
  }

  if options[:only]
    options[:only].each do |action|
      match actions[action][:path], to: "#{obj}##{action}", verb: actions[action][:verb]
    end
  elsif options[:except]
    actions.each do |action, value|
      next if options[:except].include?(action)

      match value[:path], to: "#{obj}##{action}", verb: value[:verb]
    end
  else
    actions.each do |action, value|
      match value[:path], to: "#{obj}##{action}", verb: value[:verb]
    end
  end
end

#root(dest) ⇒ Object



7
8
9
10
11
12
13
14
# File 'lib/wings/routing.rb', line 7

def root(dest)
  @rules.push(
    {
      regex:   Regexp.new("^/?$"),
      options: { to: dest, verb: :GET },
    }
  )
end