From 00898778a7262579f29565659e4de9ac37e6bd1d Mon Sep 17 00:00:00 2001 From: Matt Conway Date: Mon, 20 Sep 2021 09:39:21 -0400 Subject: [PATCH] add the typify filter --- README.md | 1 + lib/kubetruth/template.rb | 17 +++++++++ spec/kubetruth/template_spec.rb | 68 +++++++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+) diff --git a/README.md b/README.md index 5fb89f7..8d8f7f9 100644 --- a/README.md +++ b/README.md @@ -184,6 +184,7 @@ ones: | `decode64` | The argument bas64 decoded | | `sha256` | The sha256 digest of the argument | | `inflate` | Converts a map of key/values into a nested data structure based on a delimiter in the key name, e.g. `{foo.baz.bum: 2}` => `{foo: {bar: {baz: 2}}}` | +| `typify` | Converts string values into primitive types (int, float, bool) where applicable for a nested data structure | The default `resource_templates` make use of the `context` attribute to allow simpler modification of some common fields. These include: diff --git a/lib/kubetruth/template.rb b/lib/kubetruth/template.rb index a5f73ae..284f299 100644 --- a/lib/kubetruth/template.rb +++ b/lib/kubetruth/template.rb @@ -144,6 +144,23 @@ def inflate(map, delimiter='\.') result end + def typify(data) + case data + when Hash + Hash[data.collect {|k,v| [k, typify(v)] }] + when Array + data.collect {|v| typify(v) } + when /^[0-9]+$/ + data.to_i + when /^[0-9\.]+$/ + data.to_f + when /true|false/ + data == "true" + else + data + end + end + end Liquid::Template.register_filter(CustomLiquidFilters) diff --git a/spec/kubetruth/template_spec.rb b/spec/kubetruth/template_spec.rb index 4892426..712e432 100644 --- a/spec/kubetruth/template_spec.rb +++ b/spec/kubetruth/template_spec.rb @@ -235,6 +235,74 @@ module Kubetruth end + describe "#typify" do + + it "works with empty" do + expect(typify(nil)).to eq(nil) + expect(typify("")).to eq("") + expect(typify(true)).to eq(true) + expect(typify(3)).to eq(3) + expect(typify(3.4)).to eq(3.4) + expect(typify({})).to eq({}) + expect(typify([])).to eq([]) + end + + it "converts string to type" do + expect(typify("hello")).to eq("hello") + expect(typify("true")).to eq(true) + expect(typify("false")).to eq(false) + expect(typify("3")).to eq(3) + expect(typify("3.4")).to eq(3.4) + end + + it "recursively typifys structure" do + data = { + "top" => { + "mid" => [ + { + "bottom" => "1" + }, + { + "bottom" => "1.2" + }, + { + "bottom" => "true" + }, + { + "bottom" => "false" + }, + { + "bottom" => "hello" + } + ] + } + } + result = { + "top" => { + "mid" => [ + { + "bottom" => 1 + }, + { + "bottom" => 1.2 + }, + { + "bottom" => true + }, + { + "bottom" => false + }, + { + "bottom" => "hello" + } + ] + } + } + expect(typify(data)).to eq(result) + end + + end + end describe Kubetruth::Template::TemplateHashDrop do