Class: ReverseMarkdown::Mapper

Inherits:
Object
  • Object
show all
Defined in:
lib/reverse_markdown/mapper.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Mapper

Returns a new instance of Mapper.



8
9
10
11
12
13
# File 'lib/reverse_markdown/mapper.rb', line 8

def initialize(opts={})
  self.log_level   = :info
  self.log_enabled = true
  self.li_counter  = 0
  self.github_style_code_blocks = opts[:github_style_code_blocks] || false
end

Instance Attribute Details

#github_style_code_blocksObject

Returns the value of attribute github_style_code_blocks.



6
7
8
# File 'lib/reverse_markdown/mapper.rb', line 6

def github_style_code_blocks
  @github_style_code_blocks
end

#li_counterObject

Returns the value of attribute li_counter.



5
6
7
# File 'lib/reverse_markdown/mapper.rb', line 5

def li_counter
  @li_counter
end

#log_enabledObject

Returns the value of attribute log_enabled.



4
5
6
# File 'lib/reverse_markdown/mapper.rb', line 4

def log_enabled
  @log_enabled
end

#log_levelObject

Returns the value of attribute log_level.



4
5
6
# File 'lib/reverse_markdown/mapper.rb', line 4

def log_level
  @log_level
end

#raise_errorsObject

Returns the value of attribute raise_errors.



3
4
5
# File 'lib/reverse_markdown/mapper.rb', line 3

def raise_errors
  @raise_errors
end

Instance Method Details

#process_element(element) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/reverse_markdown/mapper.rb', line 46

def process_element(element)
  output = ''
  if element.text?
    text = process_text(element)
    if output.end_with?(' ') && text.start_with?(' ')
      output << text.lstrip
    else
      output << text
    end
  else
    output << opening(element).to_s

    markdown_chunks = element.children.map { |child| process_element(child) }
    remove_adjacent_whitespace!(markdown_chunks)
    output << markdown_chunks.join

    output << ending(element).to_s
  end
  output
end

#process_root(element) ⇒ Object



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
42
43
44
# File 'lib/reverse_markdown/mapper.rb', line 15

def process_root(element)
  return '' if element.nil?

  markdown = process_element(element)  # recursively process all elements to get full markdown

  # Extract github style code blocks
  extractions = {}
  markdown.gsub!(%r{```.*?```}m) do |match|
    md5 = Digest::MD5.hexdigest(match)
    extractions[md5] = match
    "{code-block-extraction-#{md5}}"
  end

  markdown = markdown.split("\n").map do |line|
    if line.match(/^( {4}|\t)/)
      line
    else
      "#{ '  ' if line.match(/^ {2,3}/) }" +
      normalize_whitespace(line).strip +
      "#{ '  ' if line.match(/ {2}$/) }"
    end
  end.join("\n")

  markdown.gsub!(/\n{3,}/, "\n\n")

  # Insert pre block extractions
  markdown.gsub!(/\{code-block-extraction-([0-9a-f]{32})\}/){ extractions[$1] }

  markdown
end