Class: Olelo::Routing::Router

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/olelo/routing.rb

Constant Summary collapse

SYNTAX =
{
  '\(' => '(?:', '\)' => ')?',
  '\{' => '(?:', '\}' => ')',
  '\|' => '|'
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRouter

Returns a new instance of Router.



146
147
148
# File 'lib/olelo/routing.rb', line 146

def initialize
  @head, @tail = [], []
end

Instance Attribute Details

#headObject (readonly)

Returns the value of attribute head.



144
145
146
# File 'lib/olelo/routing.rb', line 144

def head
  @head
end

#tailObject (readonly)

Returns the value of attribute tail.



144
145
146
# File 'lib/olelo/routing.rb', line 144

def tail
  @tail
end

Instance Method Details

#add(function, path, patterns = {}) ⇒ Object



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/olelo/routing.rb', line 165

def add(function, path, patterns = {})
  tail = patterns.delete(:tail)
  pattern = Regexp.escape(path)
  SYNTAX.each_pair {|k,v| pattern.gsub!(k, v) }
  keys = []
  pattern.gsub!(/:(\w+)/) do
    keys << $1
    patterns.key?($1) ? "(#{patterns[$1]})" : "([^/?&#\.]+)"
  end
  pattern = /^#{pattern}$/

  if i = @head.index {|x| x.first == path }
    @head[i] = [path, pattern, keys, function]
  elsif i = @tail.index {|x| x.first == path }
    @tail[i] = [path, pattern, keys, function]
  else
    (tail ? @tail : @head) << [path, pattern, keys, function]
  end
end

#each(&block) ⇒ Object



160
161
162
163
# File 'lib/olelo/routing.rb', line 160

def each(&block)
  @head.each(&block)
  @tail.each(&block)
end

#find(path) ⇒ Object



150
151
152
153
154
155
156
157
158
# File 'lib/olelo/routing.rb', line 150

def find(path)
  each do |name, pattern, keys, function|
    if match = pattern.match(path)
      params = {}
      keys.zip(match.captures.to_a).each {|k, v| params[k] = v if !v.blank? }
      yield(name, params, function)
    end
  end
end