Class: Sawtooth::Rules::TextRule

Inherits:
Base
  • Object
show all
Defined in:
lib/sawtooth/rules/text_rule.rb

Overview

Sets a value on an object on the stack based on the text contents of a tag.

Inputs can further be converted by supplying a custom block which converts the input, this is useful to perform e.g. parsing dates or similar.

Constant Summary collapse

CONVERTER =

Default Text Converter

Proc.new { |input| input = input.strip; input.length > 0 ? input : nil }

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#print_rule, #start

Constructor Details

#initialize(name = nil, &block) ⇒ TextRule

Returns a new instance of TextRule.



21
22
23
24
# File 'lib/sawtooth/rules/text_rule.rb', line 21

def initialize(name = nil, &block)
  @name = name
  @converter = block_given? ? block : CONVERTER
end

Instance Attribute Details

#converterObject (readonly)

Settings



19
20
21
# File 'lib/sawtooth/rules/text_rule.rb', line 19

def converter
  @converter
end

#nameObject (readonly)

Settings



19
20
21
# File 'lib/sawtooth/rules/text_rule.rb', line 19

def name
  @name
end

Instance Method Details

#finish(path, doc, node) ⇒ Object

If theres some text, send it to reciever (top object).



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/sawtooth/rules/text_rule.rb', line 27

def finish(path, doc, node)
  value = converter.call(node.text)
  attr_name = (self.name.respond_to?(:call) ? self.name.call(node.name) : self.name) || underscore(node.name)
  obj = doc.top

  case
    when obj.respond_to?("#{attr_name}="); obj.send("#{attr_name}=", value)
    when obj.respond_to?(:key?); obj[attr_name] = value
    when obj.respond_to?(:push); obj.push value
    # else, warning...?
  end if value
end