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.



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

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.



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

def filename
  @filename
end

#merge_hashObject (readonly)

Returns the value of attribute merge_hash.



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

def merge_hash
  @merge_hash
end

Class Method Details

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



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

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

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

.from_str(command, params) ⇒ Object



7
8
9
# File 'lib/pups/merge_command.rb', line 7

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

.parse_command(command) ⇒ Object

Raises:

  • (ArgumentError)


11
12
13
14
15
16
# File 'lib/pups/merge_command.rb', line 11

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

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

Instance Method Details

#runObject



26
27
28
29
30
# File 'lib/pups/merge_command.rb', line 26

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