Class: Mato::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/mato/converter.rb

Constant Summary collapse

FLAVORES =
Set.new([
  :redcarpet, # legacy GFM uses it
]).freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(processor, content, flavor) ⇒ Converter

Returns a new instance of Converter.



20
21
22
23
24
25
26
27
28
29
# File 'lib/mato/converter.rb', line 20

def initialize(processor, content, flavor)
  unless FLAVORES.include?(flavor)
    raise "Unsupported flavor #{flavor.inspect}, it must be one of: #{FLAVORES.map(&:inspect).join(' ')}"
  end

  @processor = processor
  @content = content
  @content_lines = content.split(/\n/)
  @flavor = flavor
end

Instance Attribute Details

#contentObject (readonly)

Returns the value of attribute content.



14
15
16
# File 'lib/mato/converter.rb', line 14

def content
  @content
end

#content_linesArray<String> (readonly)

Returns:

  • (Array<String>)


18
19
20
# File 'lib/mato/converter.rb', line 18

def content_lines
  @content_lines
end

#flavorObject (readonly)

Returns the value of attribute flavor.



15
16
17
# File 'lib/mato/converter.rb', line 15

def flavor
  @flavor
end

#processorObject (readonly)

Returns the value of attribute processor.



13
14
15
# File 'lib/mato/converter.rb', line 13

def processor
  @processor
end

Instance Method Details

#convert_headings!(document) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mato/converter.rb', line 45

def convert_headings!(document)
  document.walk.select do |node|
    node.type == :text &&
      node.source_position[:start_column] == 1 &&
      node.parent.type == :paragraph &&
      node.parent.parent.type == :document
  end.reverse_each do |node|
    replacement = node.string_content.gsub(/\A(#+)(?=\S)/, '\1 ')

    if node.string_content != replacement
      pos = node.source_position
      content_lines[pos[:start_line] - 1][(pos[:start_column] - 1)...pos[:end_column]] = replacement
    end
  end
end

#runObject



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/mato/converter.rb', line 31

def run
  # @type [Commonmarker::Node]
  document = processor.parse_markdown(content)

  convert_headings!(document)

  content_lines.join("\n").tap do |c|
    # fixup newlines removed by String#split
    content.scan(/\n+\z/) do |matched|
      c << matched
    end
  end
end