Skip to content

Commit

Permalink
add a re_contains filter for rgex string comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
wr0ngway committed Jan 20, 2022
1 parent a3a6cab commit 464b848
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ ones:
| `typify` | Converts string values into primitive types (int, float, bool) where applicable for a nested data structure |
| `merge` | Combines two hashes into one, a.l.a ruby merge |
| `re_replace` | Regexp search and replace, a.l.a ruby gsub, e.g. `"foo" | re_replace: "o+", "X"` |
| `re_contains` | Returns a boolean for the regexp compare against the string target, e.g. `"foo" | re_contains: "o+"` => `true` |

The default `resource_templates` make use of the `context` attribute to allow
simpler modification of some common fields. These include:
Expand Down
5 changes: 5 additions & 0 deletions lib/kubetruth/template.rb
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,11 @@ def re_replace(string, pattern, replacement, flags="")
string.gsub(Regexp.new(pattern, allflags), replacement)
end

def re_contains(string, pattern, flags="")
allflags = flags.chars.inject(0) {|sum, n| sum | REGEXP_FLAGS[n] }
return (string =~ Regexp.new(pattern, allflags)) != nil
end

end

Liquid::Template.register_filter(CustomLiquidFilters)
Expand Down
18 changes: 18 additions & 0 deletions spec/kubetruth/template_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,24 @@ module Kubetruth
end

end

describe "#re_contains" do

it "performs match" do
expect(re_contains("foobar", "o+")).to eq(true)
expect(re_contains("foobar", "x+")).to eq(false)
expect(described_class.new('{{ "foobar" | re_contains: "o+" }}').render()).to eq("true")
end

it "handles flags" do
expect(re_contains("fOObar", "o+")).to eq(false)
expect(re_contains("fOObar", "o+", "i")).to eq(true)
expect(re_contains("FOO\nOO", "f.{5}", "i")).to eq(false)
expect(re_contains("FOO\nOO", "f.{5}", "mi")).to eq(true)
end

end

end

describe Kubetruth::Template::TemplateHashDrop do
Expand Down

0 comments on commit 464b848

Please sign in to comment.