Class: Furigana::Formatter::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/furigana/formatter/base.rb

Direct Known Subclasses

HTML, JSON, Text

Class Method Summary collapse

Class Method Details

.format(text, tokens) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/furigana/formatter/base.rb', line 6

def format(text, tokens)
  surface_form, reading = 0, 1
  new_text = ''
  tokens_enum = tokens.to_enum
  begin
    current_token = tokens_enum.next
  rescue StopIteration
    current_token = nil
  end
  substring, pos = "", 0

  text.each_char do |char|
    if current_token
      substring += char
      if char == current_token[surface_form][pos]
        if pos == current_token[surface_form].length-1
          new_text += replacement(current_token[surface_form], current_token[reading])
          begin
            current_token = tokens_enum.next
          rescue StopIteration
            current_token = nil
          end
          substring, pos = "", 0
        else
          pos += 1
        end
      else # not a match
        new_text += substring
        substring, pos = "", 0
      end
    else # no more tokens
      new_text += char
    end
  end
  new_text
end