Class: Polytrix::DocumentationGenerator

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(template_file = nil, scenario = nil) ⇒ DocumentationGenerator

Returns a new instance of DocumentationGenerator.



18
19
20
21
# File 'lib/polytrix/documentation_generator.rb', line 18

def initialize(template_file = nil, scenario = nil)
  @scenario = scenario
  @template_file = template_file
end

Instance Attribute Details

#scenarioObject (readonly)

Returns the value of attribute scenario.



16
17
18
# File 'lib/polytrix/documentation_generator.rb', line 16

def scenario
  @scenario
end

Instance Method Details

#code2doc(source_file, language = nil) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/polytrix/documentation_generator.rb', line 40

def code2doc(source_file, language = nil)
  source_code = File.read(source_file)
  if language.nil?
    language, comment_style = Documentation::CommentStyles.infer File.extname(source_file)
    segmenter_language = comment_style[:language] || language
  else
    segmenter_language = language
  end

  buffer = StringIO.new
  segmenter_options = {
    language: segmenter_language
  }
  segmenter = Polytrix::Documentation::CodeSegmenter.new(segmenter_options)
  segments = segmenter.segment source_code
  segments.each do |comment, code|
    comment = comment.join("\n")
    code = code.join("\n")
    buffer.puts comment unless comment.empty?
    buffer.puts code_block code, language unless code.empty?
  end
  buffer.string
end

#process(challenges) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/polytrix/documentation_generator.rb', line 23

def process(challenges)
  return nil unless File.readable? @template_file

  @challenges = challenges
  erb = ERB.new File.read(@template_file)
  @result = erb.result(binding) || ''
end

#save(target_file) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/polytrix/documentation_generator.rb', line 31

def save(target_file)
  fail 'No results to write, please call process before save' if @result.nil? || @result.empty?

  FileUtils.mkdir_p File.dirname(target_file)
  File.open(target_file, 'wb') do |f|
    f.write @result
  end
end