Class: Starter::Markdown::CodeEmbedder

Inherits:
Object
  • Object
show all
Defined in:
lib/starter/markdown/extender.rb

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ CodeEmbedder

Returns a new instance of CodeEmbedder.



38
39
40
# File 'lib/starter/markdown/extender.rb', line 38

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

Instance Method Details

#process(lines) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/starter/markdown/extender.rb', line 43

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)
      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
      out << embed.slice(start..stop).join()
      out << "```\n"
    else
      out << line
    end
  end
  out
end