Module: Card::FileCardCreator::OutputHelper

Included in:
AbstractFileCard
Defined in:
lib/card/tasks/card/file_card_creator/output_helper.rb

Overview

Helper methods to write to files and the console.

Instance Method Summary collapse

Instance Method Details

#color_puts(colored_text, color, text = "") ⇒ Object



45
46
47
# File 'lib/card/tasks/card/file_card_creator/output_helper.rb', line 45

def color_puts colored_text, color, text=""
  puts "#{colored_text.send(color.to_s)} #{text}"
end

#log_file_action(path) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/card/tasks/card/file_card_creator/output_helper.rb', line 17

def log_file_action path
  status, color =
    if File.exist?(path) && !@force
      ["file exists (use 'force=true' to override)", :yellow]
    else
      status = File.exist?(path) ? "overridden" : "created"
      yield
      [status, :green]
    end

  color_puts status, color, path
end

#write_at(fname, at_line, sdat) ⇒ Object

insert content into a file at a given line number



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/card/tasks/card/file_card_creator/output_helper.rb', line 31

def write_at fname, at_line, sdat
  open(fname, "r+") do |f|
    (at_line - 1).times do # read up to the line you want to write after
      f.readline
    end
    pos = f.pos # save your position in the file
    rest = f.read # save the rest of the file
    f.seek pos # go back to the old position
    f.puts sdat # write new data & rest of file
    f.puts rest
    color_puts "created", :green, fname
  end
end

#write_to_mod(rel_dir, filename) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
# File 'lib/card/tasks/card/file_card_creator/output_helper.rb', line 5

def write_to_mod rel_dir, filename
  dir = File.join "mod", @mod, rel_dir
  FileUtils.mkdir_p(dir) unless Dir.exist?(dir)

  path = File.join dir, filename
  log_file_action path do
    File.open(path, "w") do |opened_file|
      yield(opened_file)
    end
  end
end