Class: Rundoc::CodeCommand::FileCommand::Append
Instance Attribute Summary
#command, #contents, #keyword, #original_args, #render_command, #render_result
Instance Method Summary
collapse
#filename, #mkdir_p
#hidden?, #not_hidden?, #push
Constructor Details
#initialize(filename) ⇒ Append
Returns a new instance of Append.
5
6
7
8
9
10
11
12
|
# File 'lib/rundoc/code_command/file_command/append.rb', line 5
def initialize(filename)
@filename, line = filename.split('#')
if line
@line_number = Integer(line)
else
@line_number = nil
end
end
|
Instance Method Details
#call(env = {}) ⇒ Object
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
# File 'lib/rundoc/code_command/file_command/append.rb', line 59
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.open(filename, "w") do |f|
f.write(doc)
end
contents
end
|
#concat_with_newline(str1, str2) ⇒ Object
35
36
37
38
39
40
41
42
|
# File 'lib/rundoc/code_command/file_command/append.rb', line 35
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
|
#ends_in_newline?(string) ⇒ Boolean
31
32
33
|
# File 'lib/rundoc/code_command/file_command/append.rb', line 31
def ends_in_newline?(string)
last_char_of(string) == "\n"
end
|
#insert_contents_into_at_line(doc) ⇒ Object
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
# File 'lib/rundoc/code_command/file_command/append.rb', line 44
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
doc = result.flatten.join("")
end
|
#last_char_of(string) ⇒ Object
27
28
29
|
# File 'lib/rundoc/code_command/file_command/append.rb', line 27
def last_char_of(string)
string[-1,1]
end
|
#to_md(env) ⇒ Object
14
15
16
17
18
19
20
21
22
23
24
25
|
# File 'lib/rundoc/code_command/file_command/append.rb', line 14
def to_md(env)
return unless render_command?
raise "must call write in its own code section" unless env[:commands].empty?
before = env[:before]
if @line_number
env[:before] = "In file `#{filename}`, on line #{@line_number} add:\n\n#{before}"
else
env[:before] = "At the end of `#{filename}` add:\n\n#{before}"
end
nil
end
|