Class: Pups::MergeCommand

Inherits:
Command
  • Object
show all
Defined in:
lib/pups/merge_command.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Command

#interpolate_params, interpolate_params, run

Constructor Details

#initialize(command, params) ⇒ MergeCommand

Returns a new instance of MergeCommand.



16
17
18
19
20
21
22
# File 'lib/pups/merge_command.rb', line 16

def initialize(command, params)
  @params = params

  filename, target_param = Pups::MergeCommand.parse_command(command)
  @filename = interpolate_params(filename)
  @merge_hash = params[target_param]
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename.



2
3
4
# File 'lib/pups/merge_command.rb', line 2

def filename
  @filename
end

#merge_hashObject (readonly)

Returns the value of attribute merge_hash.



3
4
5
# File 'lib/pups/merge_command.rb', line 3

def merge_hash
  @merge_hash
end

Class Method Details

.deep_merge(first, second, *args) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/pups/merge_command.rb', line 30

def self.deep_merge(first,second, *args)
  args ||= []
  merge_arrays = args.include? :merge_arrays

  merger = proc { |key, v1, v2|
    if Hash === v1 && Hash === v2
      v1.merge(v2, &merger)
    elsif Array === v1 && Array === v2
      merge_arrays ? v1 + v2 : v2
    elsif NilClass === v2
      v1
    else
      v2
    end
  }
  first.merge(second, &merger)
end

.from_str(command, params) ⇒ Object



5
6
7
# File 'lib/pups/merge_command.rb', line 5

def self.from_str(command, params)
  new(command,params)
end

.parse_command(command) ⇒ Object

Raises:

  • (ArgumentError)


9
10
11
12
13
14
# File 'lib/pups/merge_command.rb', line 9

def self.parse_command(command)
  split = command.split(" ")
  raise ArgumentError.new("Invalid merge command #{command}") unless split[-1][0] == "$"

  [split[0..-2].join(" ") , split[-1][1..-1]]
end

Instance Method Details

#runObject



24
25
26
27
28
# File 'lib/pups/merge_command.rb', line 24

def run
  merged = self.class.deep_merge(YAML.load_file(@filename), @merge_hash)
  File.open(@filename,"w"){|f| f.write(merged.to_yaml) }
  Pups.log.info("Merge: #{@filename} with: \n#{@merge_hash.inspect}")
end