Class: PFM::CodeBlockInclude

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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ CodeBlockInclude

Returns a new instance of CodeBlockInclude.



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

def initialize(options={})
  @regex = %r{^```([^\s#]+)(#L(\S+))?\s*```$}
end

Instance Method Details

#process(lines) ⇒ Object



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
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/pfm.rb', line 18

def process(lines)
  # TODO: handle URLs
  out = []
  lines.each do |line|
    if md = @regex.match(line)
      _full, source_path, badline, line_spec = md.to_a
      if line_spec
        start, stop = line_spec.split("-").map { |s| s.to_i}
      else
        start = 1
      end

      source_path = File.expand_path(source_path).strip
      extension = File.extname(source_path).slice(1..-1)
      out << "```#{extension}"

      embed = []
      File.open(source_path, "r") do |source|
        source.each_line do |line|
          embed << line
        end
      end
      start -= 1
      if stop
        stop -=1
      else
        stop = embed.size - 1
      end
      selection = embed.slice(start..stop)
      while selection.last =~ /^\s+$/
        selection.pop
      end
      out << selection.join()
      out << "```\n"
    else
      out << line
    end
  end
  out
end