class Rundoc::CodeCommand::FileCommand::Append
Public Class Methods
Source
# File lib/rundoc/code_command/file_command/append.rb, line 5 def initialize(filename) @filename, line = filename.split("#") @line_number = if line Integer(line) end end
Public Instance Methods
Source
# File lib/rundoc/code_command/file_command/append.rb, line 60 def call(env = {}) mkdir_p doc = File.read(filename) if @line_number puts "Writing to: '#{filename}' line #{@line_number} with: #{contents.inspect}" doc = insert_contents_into_at_line(doc) else puts "Appending to file: '#{filename}' with: #{contents.inspect}" doc = concat_with_newline(doc, contents) end File.write(filename, doc) contents end
Source
# File lib/rundoc/code_command/file_command/append.rb, line 36 def concat_with_newline(str1, str2) result = "" result << str1 result << "\n" unless ends_in_newline?(result) result << str2 result << "\n" unless ends_in_newline?(result) result end
Source
# File lib/rundoc/code_command/file_command/append.rb, line 32 def ends_in_newline?(string) last_char_of(string) == "\n" end
Source
# File lib/rundoc/code_command/file_command/append.rb, line 45 def insert_contents_into_at_line(doc) lines = doc.lines raise "Expected #{filename} to have at least #{@line_number} but only has #{lines.count}" if lines.count < @line_number result = [] lines.each_with_index do |line, index| line_number = index.next if line_number == @line_number result << contents result << "\n" unless ends_in_newline?(contents) end result << line end result.flatten.join("") end
Source
# File lib/rundoc/code_command/file_command/append.rb, line 28 def last_char_of(string) string[-1, 1] end
Source
# File lib/rundoc/code_command/file_command/append.rb, line 12 def to_md(env) return unless render_command? if env[:commands].any? { |c| c[:object].not_hidden? } raise "Must call append in its own code section" end env[:before] << if @line_number "In file `#{filename}`, on line #{@line_number} add:" else "At the end of `#{filename}` add:" end env[:before] << NEWLINE nil end