class Rundoc::CodeSection

holds code, parses and creates CodeCommand

Constants

AUTOGEN_WARNING
COMMAND_REGEX

Attributes

code[RW]
commands[RW]
fence[RW]
keyword[RW]
lang[RW]
original[RW]

Public Class Methods

new(match, keyword:, context:) click to toggle source
# File lib/rundoc/code_section.rb, line 31
def initialize(match, keyword:, context:)
  @original = match.to_s
  @commands = []
  @stack = []
  @keyword = keyword
  @context = context
  @fence = match[:fence]
  @lang = match[:lang]
  @code = match[:contents]
  parse_code_command
end

Public Instance Methods

hidden?() click to toggle source

all of the commands are hidden

# File lib/rundoc/code_section.rb, line 99
def hidden?
  !not_hidden?
end
not_hidden?() click to toggle source

one or more of the commands are not hidden

# File lib/rundoc/code_section.rb, line 104
def not_hidden?
  return true if commands.empty?
  commands.map(&:not_hidden?).detect { |c| c }
end
parse_code_command() click to toggle source
# File lib/rundoc/code_section.rb, line 109
def parse_code_command
  parser = Rundoc::PegParser.new.code_block
  tree = parser.parse(@code)
  actual = Rundoc::PegTransformer.new.apply(tree)
  actual = [actual] unless actual.is_a?(Array)
  actual.each do |code_command|
    @stack << "\n" if commands.last.is_a?(Rundoc::CodeCommand)
    @stack << code_command
    commands << code_command
  end
rescue ::Parslet::ParseFailed => e
  raise "Could not compile code:\n#{@code}\nReason: #{e.message}"
end
render() click to toggle source
# File lib/rundoc/code_section.rb, line 43
def render
  result = []
  env = {}
  env[:commands] = []
  env[:fence_start] = +"#{fence}#{lang}"
  env[:fence_end] = "#{fence}#{AUTOGEN_WARNING}"
  env[:before] = []
  env[:after] = []
  env[:context] = @context

  @stack.each do |s|
    unless s.respond_to?(:call)
      result << s
      next
    end

    code_command = s
    code_output = code_command.call(env) || ""
    code_line = code_command.to_md(env) || ""

    env[:commands] << {object: code_command, output: code_output, command: code_line}

    tmp_result = []
    tmp_result << code_line if code_command.render_command?
    tmp_result << code_output if code_command.render_result?

    result << tmp_result unless code_command.hidden?
  end

  return "" if hidden?

  array = [env[:before]]

  result.flatten!
  result.compact!
  result.map! { |s| s.respond_to?(:rstrip) ? s.rstrip : s }
  result.reject!(&:empty?)
  result.map!(&:to_s)

  if !result.empty?
    array << env[:fence_start]
    array << result
    array << env[:fence_end]
  end
  array << env[:after]

  array.flatten!
  array.compact!
  array.map! { |s| s.respond_to?(:rstrip) ? s.rstrip : s }
  array.reject!(&:empty?)
  array.map!(&:to_s)

  array.join("\n") << "\n"
end