Class: JSGF::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/jsgf/builder.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBuilder

Returns a new instance of Builder.



6
7
8
# File 'lib/jsgf/builder.rb', line 6

def initialize
    @rules = {}
end

Class Method Details

.build(name = nil, &block) ⇒ Grammar

Convenience method for instantiating a builder and then building a Grammar

Parameters:

  • name (String) (defaults to: nil)

    the name of the new Grammar

Returns:



13
14
15
# File 'lib/jsgf/builder.rb', line 13

def self.build(name=nil, &block)
    self.new.build(name, &block)
end

Instance Method Details

#build(name = nil, &block) ⇒ Grammar

Returns a new Grammar built from the block argument.

Parameters:

  • name (String) (defaults to: nil)

    the name of the new Grammar

Returns:



19
20
21
22
23
# File 'lib/jsgf/builder.rb', line 19

def build(name=nil, &block)
    @name = name || 'DSL'
    instance_eval(&block) if block_given?
    Grammar.new(name:@name, rules:@rules)
end

#name(arg) ⇒ Object

Set the name attribute from the DSL block



26
27
28
# File 'lib/jsgf/builder.rb', line 26

def name(arg)
    @name = arg
end

#rule(**options) ⇒ JSGF::Grammar

Create a new rule using the provided name and string

By default, all new rules are private, unless they're root rules

Examples:

rule rule1: 'This is a rule'
rule rule2: ['one', 'two']
rule rule3: 'This is not :rule2'

Returns:



37
38
39
40
41
42
43
44
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/jsgf/builder.rb', line 37

def rule(**options)
    options.each do |name, v|
	@rules[name.to_s] = case v
	    when Array	then Rule.new [Alternation.new(*v)]
	    when Symbol	then Rule.new [Rule.parse_atom(v.to_s).tap {|a| a.reference=true}]
	    else
		stack = nil
		v.split(' ').map do |a|
		    if stack
			if a == ']'
			    next if stack.empty?

			    if stack.length == 1
				stack.first.optional = true
				stack.first
			    else
				Optional.new(*stack)
			    end.tap do
				stack = nil
			    end
			else
			    stack.push(Rule.parse_atom(a))
			    next
			end
		    elsif a == '['
			stack = []
			next
		    else
			Rule.parse_atom(a)
		    end
		end.compact
	end
    end
end