Class: TemplateExpander

Inherits:
Object
  • Object
show all
Defined in:
lib/HDLRuby/template_expander.rb

Defined Under Namespace

Classes: Rule

Instance Method Summary collapse

Constructor Details

#initialize(rules = []) ⇒ TemplateExpander

Creates a new template expander with potential list of +rules+.



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/HDLRuby/template_expander.rb', line 17

def initialize(rules= [])
    # Setup the rules.
    @rules = rules.map do |match,action|
        # Ensures action is a proc.
        action = proc { |str| action.to_s } unless action.is_a?(Proc)
        # Create the rule.
        Rule.new(Regexp.new(match), action)
    end
    # The skip regexp is empty, it has to be built with finalize.
    @skip = nil
end

Instance Method Details

#add_rule(*rule) ⇒ Object

Adds a +rule+.



30
31
32
# File 'lib/HDLRuby/template_expander.rb', line 30

def add_rule(*rule)
    @rules << Rule.new(Regexp.new(rule[0]), rule[1])
end

#expand(str, res = "") ⇒ Object

Apply the expander to +str+ and put the result in +res+.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/HDLRuby/template_expander.rb', line 41

def expand(str,res = "")
    # Ensure the default rule is properly set up.
    self.finalize
    # Scan the string with each rule.
    scanner = StringScanner.new(str)
    until scanner.eos? do
        @rules.find do |rule|
            scanned = scanner.scan(rule.match)
            if scanned then
                res << rule.action.call(scanned)
            else
                false
            end
        end
        res << scanner.scan_until(@skip)
    end
    return res
end

#finalizeObject

Finalize the expander by building the default rule.



35
36
37
38
# File 'lib/HDLRuby/template_expander.rb', line 35

def finalize
    # @skip = Regexp.union(*@rules.map { |rule| rule.match })
    @skip = /(?=#{Regexp.union(*@rules.map { |rule| rule.match }).source})|\z/
end