Skip to content

Commit

Permalink
add the typify filter
Browse files Browse the repository at this point in the history
  • Loading branch information
wr0ngway committed Sep 20, 2021
1 parent 6f272c2 commit 0089877
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
17 changes: 17 additions & 0 deletions lib/kubetruth/template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
68 changes: 68 additions & 0 deletions spec/kubetruth/template_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 0089877

Please sign in to comment.