Module: Card::FileCardCreator::OutputHelper

Included in:
AbstractFileCard
Defined in:
card/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



48
49
50
# File 'card/lib/card/tasks/card/file_card_creator/output_helper.rb', line 48

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

#execute_and_log_file_action(path) ⇒ Object



23
24
25
26
27
# File 'card/lib/card/tasks/card/file_card_creator/output_helper.rb', line 23

def execute_and_log_file_action path
  status = File.exist?(path) ? "overridden" : "created"
  yield
  color_puts status, :green, path
end

#log_file_action(path, &block) ⇒ Object



15
16
17
18
19
20
21
# File 'card/lib/card/tasks/card/file_card_creator/output_helper.rb', line 15

def log_file_action path, &block
  if File.exist?(path) && !@force
    log_file_exists path
  else
    execute_and_log_file_action path, &block
  end
end

#log_file_exists(path) ⇒ Object



29
30
31
# File 'card/lib/card/tasks/card/file_card_creator/output_helper.rb', line 29

def log_file_exists path
  color_puts "file exists (use 'force=true' to override)", :yellow, path
end

#write_at(fname, at_line, sdat) ⇒ Object

insert content into a file at a given line number



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'card/lib/card/tasks/card/file_card_creator/output_helper.rb', line 34

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, &block) ⇒ Object



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

def write_to_mod rel_dir, filename, &block
  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", &block)
  end
end