Module: DiceBag::DiceBagFile

Included in:
ConfigFile, DefaultTemplateFile, TemplateFile
Defined in:
lib/dice_bag/dice_bag_file.rb

Constant Summary collapse

@@force =
false

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#fileObject (readonly)

Returns the value of attribute file


7
8
9
# File 'lib/dice_bag/dice_bag_file.rb', line 7

def file
  @file
end

#filenameObject (readonly)

Returns the value of attribute filename


7
8
9
# File 'lib/dice_bag/dice_bag_file.rb', line 7

def filename
  @filename
end

Instance Method Details

#assert_existenceObject


10
11
12
13
14
# File 'lib/dice_bag/dice_bag_file.rb', line 10

def assert_existence
  unless File.exists?(@file)
    raise "File #{@file} not found. Configuration file not created"
  end
end

#should_write?(new_contents) ⇒ Boolean

Returns:

  • (Boolean)

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/dice_bag/dice_bag_file.rb', line 22

def should_write?(new_contents)
  #we always overwrite if we are inside an script or we are not development
  return true if @@force || !$stdin.tty? || ENV['RAILS_ENV'] == 'test' || ENV['RAILS_ENV'] == 'production'
  return true if !File.exists?(file)
  return false if diff(file, new_contents).empty?

  while true
    puts "Overwrite #{file} ?    Recommended: Yes. "
    puts " [Y]es, [n]o, [a]ll files, [q]uit, [d]show diff"
    answer = $stdin.gets.tap{|text| text.strip!.downcase! if text}
    case answer
    when 'y'
      return true
    when 'n'
      return false
    when 'a'
      return @@force = true
    when 'q'
      exit
    when 'd'
      puts diff(file, new_contents)
    else
      return true
    end
  end
end

#write(contents) ⇒ Object


16
17
18
19
20
# File 'lib/dice_bag/dice_bag_file.rb', line 16

def write(contents)
  File.open(@file, 'w') do |file|
    file.puts(contents)
  end
end