Class: Brut::CLI::Apps::New::Ops::InsertIntoFile
- Defined in:
- lib/brut/cli/apps/new/ops/insert_into_file.rb
Instance Method Summary collapse
-
#call ⇒ Object
-
#initialize(file:, content:, before_line:) ⇒ InsertIntoFile
constructor
A new instance of InsertIntoFile.
Methods inherited from BaseOp
dry_run=, dry_run?, #dry_run?, fileutils_args, #fileutils_args
Constructor Details
#initialize(file:, content:, before_line:) ⇒ InsertIntoFile
Returns a new instance of InsertIntoFile.
2 3 4 5 6 |
# File 'lib/brut/cli/apps/new/ops/insert_into_file.rb', line 2 def initialize(file:, content:, before_line:) @file = file @content = content @before_line = before_line end |
Instance Method Details
#call ⇒ Object
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/brut/cli/apps/new/ops/insert_into_file.rb', line 8 def call contents = File.read(@file) locations = [] new_contents = [] contents.split("\n").each_with_index do |line, index| if line == @before_line new_contents << @content locations << (index + 1) end new_contents << line end if locations.empty? raise "Did not find line '#{@before_line}' exactly in #{@file}" end if locations.size > 1 raise "Found exact line '#{@before_line}' #{locations.size} times in #{@file}, should be exactly once so we know where to insert" end if dry_run? puts "Would add to #{@file}, resulting in this content:\n#{new_contents.join("\n")}\n" return end File.open(@file, "w") do |file| file.puts new_contents.join("\n") end end |