Module: K8s::Util
- Defined in:
- lib/k8s/util.rb
Overview
Miscellaneous helpers
Class Method Summary collapse
-
.compact_map(args) {|args| ... } ⇒ Array<nil, Object>
Yield with all non-nil args, returning matching array with corresponding return values or nils.
-
.json_patch(a, b) ⇒ Object
Produces a set of json-patch operations so that applying the operations on a, gives you the results of b Used in correctly patching the Kube resources on stack updates.
Class Method Details
.compact_map(args) {|args| ... } ⇒ Array<nil, Object>
Yield with all non-nil args, returning matching array with corresponding return values or nils.
Args must be usable as hash keys. Duplicate args will all map to the same return value.
12 13 14 15 16 17 18 19 20 21 |
# File 'lib/k8s/util.rb', line 12 def self.compact_map(args) func_args = args.compact values = yield func_args # Hash{arg => value} value_map = Hash[func_args.zip(values)] args.map{|arg| value_map[arg] } end |
.json_patch(a, b) ⇒ Object
Produces a set of json-patch operations so that applying the operations on a, gives you the results of b Used in correctly patching the Kube resources on stack updates
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 58 59 60 61 62 63 |
# File 'lib/k8s/util.rb', line 29 def self.json_patch(a, b) diffs = HashDiff.diff(a, b, array_path: true) ops = [] # Each diff is like ["+", "spec.selector.aziz", "kebab"] # or ["-", "spec.selector.aziz", "kebab"] diffs.each do |diff| operator = diff[0] # substitute '/' with '~1' and '~' with '~0' # according to RFC 6901 path = diff[1].map {|p| p.to_s.gsub('/', '~1')}.map {|p| p.to_s.gsub('~', '~0')} if operator == '-' ops << { op: "remove", path: "/" + path.join('/') } elsif operator == '+' ops << { op: "add", path: "/" + path.join('/'), value: diff[2] } elsif operator == '~' ops << { op: "replace", path: "/" + path.join('/'), value: diff[3] } else raise "Unknown diff operator: #{operator}!" end end ops end |