Class: YAMLCommand::Command::SplatCommand

Inherits:
YAMLCommand::Command show all
Defined in:
lib/yaml_command/splat.rb

Overview

Writes each entry of a YAML hash to a file. This is the opposite of #slurp.

Instance Attribute Summary

Attributes inherited from YAMLCommand::Command

#file

Instance Method Summary collapse

Methods inherited from YAMLCommand::Command

command_name, #debug=, #debug?, #h!, #help!, #inspect=, #inspect?, #json=, #json?, #mute=, #mute?, #yaml=, #yaml?

Instance Method Details

#call(dir = nil) ⇒ Object

Splat a YAML mapping document into a directory of files. One file is created for each mapping key.



18
19
20
21
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
48
49
50
51
52
53
54
55
56
57
# File 'lib/yaml_command/splat.rb', line 18

def call(dir=nil)
  raise 'not a mapping' unless Hash === data

  dir ||= file.chomp('.yaml').chomp('.yml')

  old_map = build_old_map(dir)
  new_map = build_new_map(dir)

  # TODO: get a list of keys that will actually change

  remove = (old_map.keys - new_map.keys).sort

  if dryrun?
    save_dryrun(remove, new_map.keys)
    return
  end

  unless remove.empty? or force?
    $stderr.puts "This operation will remove:"
    remove.each do |f|
      $stderr.puts "  #{f}"
    end
    $stderr.puts "Use -f/--force option to proceed."
    return
  end

  remove.each do |f|
    FileUtils.rm_r(f) if File.exist?(f)
  end

  new_map.each do |f,v|
    if v != old_map[f]
      d = File.dirname(f)
      FileUtils.mkdir_p(d) unless File.directory?(d)
      File.open(f, 'w'){ |f| f << v }
    end
  end

  nil
end