Class: Crossroads::Match

Inherits:
Object
  • Object
show all
Includes:
Clearwater::Component
Defined in:
lib/crossroads/match.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes = {}, pattern:, component: nil, render: nil, &block) ⇒ Match

Returns a new instance of Match.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/crossroads/match.rb', line 7

def initialize(attributes = {}, pattern:, component: nil, render: nil, &block)
  @names = []
  if pattern.kind_of?(Regexp)
    @pattern = pattern
  else
    @pattern = Regexp.new( pattern.split('/').map { |part|
      md = /:([a-z]+)/.match(part)
      if md.nil?
        Regexp.escape(part)
      else
        @names << part[1..-1]
        '([^\/.+])'
      end
    }.join('\/') )
  end

  @attributes = attributes
  # @attributes[:key] ||= pattern

  @render = ->(params) { component.new(params) } if component
  @render = render               if render
  @render = block                if block
end

Instance Method Details

#renderObject



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/crossroads/match.rb', line 31

def render
  return nil if Router.matched.last == true
  location = Router.locations.last
  md = @pattern.match(location)
  return nil if md.nil?
  params = {}
  @names.each_with_index { |name, i| params[name] = md[i+1] }
  Router.locations.push(location[md.offset(0)[1]..-1])
  Router.matched.push(false)

  result = div(@attributes, [@render.call(params)])

  Router.matched.pop()
  Router.locations.pop()
  Router.matched.pop()
  Router.matched.push(true)

  return result
end