Class: Waw::Routing::ActionRouting

Inherits:
Object
  • Object
show all
Defined in:
lib/waw/routing/action_routing.rb

Overview

Routing rules installed on an action

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ ActionRouting

Creates an empty routing table. If a block is given, executes it as a Routing DSL



11
12
13
14
# File 'lib/waw/routing/action_routing.rb', line 11

def initialize(&block)
  @rules = {}
  DSL.new(self).instance_eval(&block) if block
end

Instance Method Details

#add_rules(action_results, exec) ⇒ Object

Add some routing rules



17
18
19
# File 'lib/waw/routing/action_routing.rb', line 17

def add_rules(action_results, exec)
  action_results.each {|actr| @rules[actr] = exec}
end

#apply_on_browser(result, browser) ⇒ Object

Applies this action routing on a browser



70
71
72
73
74
# File 'lib/waw/routing/action_routing.rb', line 70

def apply_on_browser(result, browser)
  @rules.each_pair do |pattern, rule|
    rule.apply_on_browser(result, browser) if Waw::Routing.matches?(pattern, result)
  end
end

#generate_js_if_then_else(table, key, level = 0, align = 0) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/waw/routing/action_routing.rb', line 21

def generate_js_if_then_else(table, key, level = 0, align = 0)
  case table
    when Hash
      if table.size==1 and table.has_key?('*')
        generate_js_if_then_else(table['*'], key, level, align)
      else
        first, buffer, space = true, "", " "
        
        # normal table
        table.each do |key, n|
          next if key=='*'
          code = "#{first ? space*align : ' else '}if (data[#{level}] == '#{key}') {\n" +
                 "#{generate_js_if_then_else(n, key, level+1, align+2)}\n" +
                 " "*align + "}"
          first = false
          buffer << code
        end
        
        if table.has_key?('*')
          buffer << " else {\n"
          buffer << generate_js_if_then_else(table['*'], key, level, align+1)
          buffer << " "*align + "}"
        end
        
        buffer
      end
    when RoutingRule
      table.generate_js_code(key, align)
    else
      raise "Unexpected table #{table}"
  end
end

#generate_js_routing(action, align = 0) ⇒ Object

Generates the javascript routing



55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/waw/routing/action_routing.rb', line 55

def generate_js_routing(action, align=0)
  # Build the if-then-else table
  table = Hash.new {|h, k| h[k] = Hash.new}
  @rules.each do |pattern, rule|
    elements = pattern.split('/')
    raise "Unsupport action-routing pattern #{pattern}" if elements.size==0 or elements.size>2
    elements << '*' if elements.size == 1
    table[elements[0]][elements[1]] = rule
  end
  
  # Build the javascript code now
  generate_js_if_then_else(table, "", 0, align)
end