module DiceBag::DiceBagFile

Attributes

destination[R]
file[R]
filename[R]

Public Instance Methods

assert_existence() click to toggle source
# File lib/dice_bag/dice_bag_file.rb, line 13
def assert_existence
  raise "File #{@file} not found. Configuration file not created" unless File.exist?(@file)
end
should_write?(new_contents) click to toggle source
# File lib/dice_bag/dice_bag_file.rb, line 23
def should_write?(new_contents)
  return true if @@overwrite_all || !File.exist?(file)
  return false if diff(file, new_contents).empty?

  # rubocop:disable Metrics/BlockLength
  loop do
    puts "Overwrite #{file} ?    Recommended: Yes. "
    puts " [Y]es, [n]o, [a]ll files, [q]uit, [d]show diff"
    answer = $stdin.gets
    answer &&= answer.chars.first.downcase
    case answer
    when "y"
      return true
    when "n"
      return false
    when "a"
      return @@overwrite_all = true
    when "q"
      exit
    when "d"
      puts diff(file, new_contents)
    else
      return true
    end
  end
  # rubocop:enable Metrics/BlockLength
end
write(contents) click to toggle source
# File lib/dice_bag/dice_bag_file.rb, line 17
def write(contents)
  File.open(@file, "w") do |file|
    file.puts(contents)
  end
end

Private Instance Methods

diff(destination, content) click to toggle source
# File lib/dice_bag/dice_bag_file.rb, line 53
def diff(destination, content)
  diff_cmd = ENV["RAILS_DIFF"] || "diff -u"
  Tempfile.open(File.basename(destination), File.dirname(destination)) do |temp|
    temp.write content
    temp.rewind
    `#{diff_cmd} #{destination} #{temp.path}`.strip
  end
end