Module: Treat::Entities::Entity::Stringable

Included in:
Treat::Entities::Entity
Defined in:
lib/treat/entities/entity/stringable.rb

Overview

Gives entities the ability to be converted to string representations (#to_string, #to_s, #to_str, #inspect, #print_tree).

Instance Method Summary collapse

Instance Method Details

#implode(value = "") ⇒ Object

Helper method to implode the string value of the subtree.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/treat/entities/entity/stringable.rb', line 61

def implode(value = "")
  
  return @value.dup if !has_children?
  
  each do |child|
    
    if child.is_a?(Treat::Entities::Section)
      value << "\n\n"
    end
    
    if child.is_a?(Treat::Entities::Token) || child.value != ''
      if child.is_a?(Treat::Entities::Punctuation) ||
        child.is_a?(Treat::Entities::Enclitic)
        value.strip!
      end
      value << child.to_s + ' '
    else
      child.implode(value)
    end
    
    if child.is_a?(Treat::Entities::Title) ||
      child.is_a?(Treat::Entities::Paragraph)
      value << "\n\n"
    end
    
  end

  value

end

#inspectObject

of the entity.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/treat/entities/entity/stringable.rb', line 42

def inspect
  name = self.class.mn
  s = "#{name} (#{@id.to_s})"
  if caller_method(2) == :inspect
    @id.to_s
  else
    edges = []
    @edges.each do |edge|
      edges <<
      "#{edge.target}#{edge.type}"
    end
    s += "  --- #{short_value.inspect}" +
    "  ---  #{@features.inspect} " +
    "  --- #{edges.inspect} "
  end
  s
end

Print out an ASCII representation of the tree.



38
# File 'lib/treat/entities/entity/stringable.rb', line 38

def print_tree; puts visualize(:tree); end

#short_value(max_length = 30) ⇒ Object

Return a shortened value of the entity’s string value using […], with a cutoff number of words or length.



28
29
30
31
32
33
34
35
# File 'lib/treat/entities/entity/stringable.rb', line 28

def short_value(max_length = 30)
  s = to_s
  words = s.split(' ')
  return s if (s.length < max_length) ||
  !(words[0..2] && words[-2..-1])
  words[0..2].join(' ') + ' [...] ' +
  words[-2..-1].join(' ')
end

#to_aObject Also known as: to_ary

Returns an array of the childrens’ string values, found by calling #to_s on them.



11
# File 'lib/treat/entities/entity/stringable.rb', line 11

def to_a; @children.map { |c| c.to_s }; end

#to_sObject Also known as: to_str

Returns the entity’s string value by imploding the value of all terminal entities in the subtree of that entity.



18
19
20
# File 'lib/treat/entities/entity/stringable.rb', line 18

def to_s
  has_children? ? implode.strip : @value.dup
end

#to_stringObject

Returns the entity’s true string value.



7
# File 'lib/treat/entities/entity/stringable.rb', line 7

def to_string;  @value.dup; end