Class: DR::SimpleKeywordsParser

Inherits:
Object
  • Object
show all
Defined in:
lib/dr/parse/simple_keywords.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash, **opts) ⇒ SimpleKeywordsParser

Returns a new instance of SimpleKeywordsParser.



5
6
7
8
# File 'lib/dr/parse/simple_keywords.rb', line 5

def initialize(hash, **opts)
	@opts=opts
	@keywords=hash
end

Instance Attribute Details

#keywordsObject

Returns the value of attribute keywords.



3
4
5
# File 'lib/dr/parse/simple_keywords.rb', line 3

def keywords
  @keywords
end

#optsObject

Returns the value of attribute opts.



3
4
5
# File 'lib/dr/parse/simple_keywords.rb', line 3

def opts
  @opts
end

Instance Method Details

#keyword(name, &b) ⇒ Object



10
11
12
# File 'lib/dr/parse/simple_keywords.rb', line 10

def keyword(name, &b)
	@keywords[name]=b
end

#parse(msg, **opts) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/dr/parse/simple_keywords.rb', line 14

def parse(msg, **opts)
	opts=@opts.merge(opts)
	sep=opts[:sep] || ','
	# Warning: the delims must take only one char
	delims= opts[:delims] || '()'
	bdelim= delims[0]
	edelim= delims[1] || bdelim
	keywords=@keywords.keys
	keywords_r="(?:"+keywords.map {|k| "(?:"+k+")"}.join("|")+")"
	reg = %r{(?<kw>#{keywords_r})(?<re>#{'\\'+bdelim}(?:(?>[^#{'\\'+bdelim}#{edelim == bdelim ? '' : '\\'+edelim}]+)|\g<re>)*#{'\\'+edelim})}
	if (m=reg.match(msg))
		arg=m[:re][1...m[:re].length-1]
		arg=parse(arg, **opts)
		args=arg.split(sep)
		args=args.map {|a| a.strip} unless opts[:space]
		key=keywords.find {|k| /#{k}/ =~ m[:kw]}
		r=@keywords[key].call(*args).to_s
		msg=m.pre_match+r+parse(m.post_match,**opts)
		msg=keywords(msg,@keywords,**opts) if opts[:recursive]
	end
	return msg
end