Class: Syobocal::Comment::Helper::Fragment

Inherits:
Object
  • Object
show all
Defined in:
lib/syobocal/comment/helper/fragment.rb

Constant Summary collapse

CHILD_BEGIN =
"("
CHILD_END =
")"
SEPARATOR =
""

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(text, child, following) ⇒ Fragment

Returns a new instance of Fragment.



11
12
13
# File 'lib/syobocal/comment/helper/fragment.rb', line 11

def initialize(text, child, following)
  @text, @child, @following = text, child, following
end

Instance Attribute Details

#childObject (readonly)

Returns the value of attribute child.



9
10
11
# File 'lib/syobocal/comment/helper/fragment.rb', line 9

def child
  @child
end

#followingObject (readonly)

Returns the value of attribute following.



9
10
11
# File 'lib/syobocal/comment/helper/fragment.rb', line 9

def following
  @following
end

#textObject (readonly)

Returns the value of attribute text.



9
10
11
# File 'lib/syobocal/comment/helper/fragment.rb', line 9

def text
  @text
end

Class Method Details

.parse(str) ⇒ Object



15
16
17
18
19
# File 'lib/syobocal/comment/helper/fragment.rb', line 15

def self.parse(str)
  chars = str.each_char.to_a

  parse_chars(chars)
end

.parse_chars(chars) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/syobocal/comment/helper/fragment.rb', line 21

def self.parse_chars(chars)
  text = ""
  child = nil
  following = nil

  until chars.empty?
    c = chars.shift

    case c
    when CHILD_BEGIN
      child = parse_chars(chars)
    when CHILD_END
      return Fragment.new(text, child, following)
    when SEPARATOR
      following = parse_chars(chars)
    else
      text << c
    end
  end

  Fragment.new(text, child, following)
end

Instance Method Details

#pretty_output(level = 0) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/syobocal/comment/helper/fragment.rb', line 44

def pretty_output(level = 0)
  line = level.times.map { " " }.join

  line << text

  puts line

  child&.pretty_output(level + 1)

  following&.pretty_output(level)
end

#to_aObject



56
57
58
59
60
61
62
63
64
65
66
# File 'lib/syobocal/comment/helper/fragment.rb', line 56

def to_a
  array = [self]
  target = self

  while target.following
    array << target.following
    target = target.following
  end

  array
end

#to_sObject



68
69
70
71
72
73
74
75
76
# File 'lib/syobocal/comment/helper/fragment.rb', line 68

def to_s
  to_a.map { |f|
    if f.child
      "#{f.text}(#{f.child.to_s})"
    else
      "#{f.text}"
    end
  }.join(SEPARATOR)
end