Skip to content

Commit

Permalink
add liquid filter deflate for completeness (inverse of inflate)
Browse files Browse the repository at this point in the history
  • Loading branch information
wr0ngway committed Nov 30, 2021
1 parent 29b9ab7 commit 1c31661
Show file tree
Hide file tree
Showing 2 changed files with 77 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/kubetruth/template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,29 @@ def decode64(str)
Base64.strict_decode64(str)
end

def deflate(hash, delimiter='.')
result = {}

hash.each do |k, v|
case v
when String, Numeric, TrueClass, FalseClass
result[k] = v
when Array
result[k] = JSON.generate(v)
when Hash
m = deflate(v, delimiter)
m.each do |mk, mv|
result["#{k}#{delimiter}#{mk}"] = mv
end
else
result[k] = v.to_s
end
end

return result
end


def inflate(map, delimiter='\.')
result = {}
map.each do |k, v|
Expand Down
54 changes: 54 additions & 0 deletions spec/kubetruth/template_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,60 @@ module Kubetruth

end

describe "#deflate" do

it "works with empty" do
expect(inflate({})).to eq({})
end

it "adds structure using delimiter" do
result = {
"topstr" => "hi",
"topnum" => 3,
"toptrue" => true,
"topfalse" => false,
"toplist" => "[1,2,3]",
"top.mid.bottom1" => 1,
"top.mid.bottom2" => 2,
"top.midval" => 3,
"other.someval" => 4
}
data = {
"topstr" => "hi",
"topnum" => 3,
"toptrue" => true,
"topfalse" => false,
"toplist" => [1, 2, 3],
"top" => {
"mid" => {
"bottom1" => 1,
"bottom2" => 2
},
"midval" => 3
},
"other" => {
"someval" => 4
}
}
expect(deflate(data)).to eq(result)
end

it "can use other delimiter" do
result = {
"top/mid/bottom1" => 1
}
data = {
"top" => {
"mid" => {
"bottom1" => 1
}
}
}
expect(deflate(data, "/")).to eq(result)
end

end

describe "#typify" do

it "works with empty" do
Expand Down

0 comments on commit 1c31661

Please sign in to comment.