Class: DoubleDoc::DocExtractor

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

Constant Summary collapse

TYPES =
{
  'rb' => /(^\s*|\s+)##\s?(?<documentation_line>.*?)(?<newline_marker>\\?)$/,
  'js' => %r{(^\s*|\s+)///\s?(?<documentation_line>.*?)(?<newline_marker>\\?)$}
}.freeze

Class Method Summary collapse

Class Method Details

.extract(source, options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/double_doc/doc_extractor.rb', line 8

def self.extract(source, options = {})
  case source
  when String
    extract_from_lines(source.split("\n"), options)
  when File
    if type = File.extname(source.path)
      type = type[1..-1]
    end
    type ||= 'rb'

    extract_from_lines(source.readlines, options.merge(:type => type))
  when Array
    extract_from_lines(source, options)
  else
    raise "can't extract docs from #{source}"
  end
end

.extract_from_lines(lines, options) ⇒ Object



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
# File 'lib/double_doc/doc_extractor.rb', line 26

def self.extract_from_lines(lines, options)
  doc = []
  extractor = TYPES[options[:type]]

  add_empty_line = false
  append_to_previous = false
  lines.each do |line|
    if match = line.match(extractor)
      if add_empty_line
        doc << ''
        add_empty_line = false
      end
      new_string = match[:documentation_line].rstrip
      if append_to_previous
        doc[-1] << new_string
      else
        doc << new_string
      end
      append_to_previous = !match[:newline_marker].empty?
    else
      add_empty_line = !doc.empty?
    end
  end

  return '' if doc.empty? || doc.all?(&:empty?)

  doc << ''

  return doc.join("\n")
end