File: delete_regex.rb

package info (click to toggle)
puppet-module-puppetlabs-stdlib 9.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,448 kB
  • sloc: ruby: 3,522; sh: 46; makefile: 2
file content (53 lines) | stat: -rw-r--r-- 1,836 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
# frozen_string_literal: true

#
#  delete_regex.rb
#  Please note: This function is an implementation of a Ruby class and as such may not be entirely UTF8 compatible. To ensure compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085.
#
module Puppet::Parser::Functions
  newfunction(:delete_regex, type: :rvalue, doc: <<-DOC
    @summary
      Deletes all instances of a given element that match a regular expression
      from an array or key from a hash.

    Multiple regular expressions are assumed to be matched as an OR.

    @example Example usage

      delete_regex(['a','b','c','b'], 'b')
      Would return: ['a','c']

      delete_regex(['a','b','c','b'], ['b', 'c'])
      Would return: ['a']

      delete_regex({'a'=>1,'b'=>2,'c'=>3}, 'b')
      Would return: {'a'=>1,'c'=>3}

      delete_regex({'a'=>1,'b'=>2,'c'=>3}, '^a$')
      Would return: {'b'=>2,'c'=>3}

    > *Note:*
    Since Puppet 4 this can be done in general with the built-in
    [`filter`](https://puppet.com/docs/puppet/latest/function.html#filter) function:
    ["aaa", "aba", "aca"].filter |$val| { $val !~ /b/ }
    Would return: ['aaa', 'aca']

    @return [Array] The given array now missing all targeted values.
  DOC
  ) do |arguments|
    raise(Puppet::ParseError, "delete_regex(): Wrong number of arguments given #{arguments.size} for 2") unless arguments.size == 2

    collection = arguments[0].dup
    Array(arguments[1]).each do |item|
      case collection
      when Array, Hash, String
        collection.reject! { |coll_item| (coll_item =~ %r{\b#{item}\b}) }
      else
        raise(TypeError, "delete_regex(): First argument must be an Array, Hash, or String. Given an argument of class #{collection.class}.")
      end
    end
    collection
  end
end

# vim: set ts=2 sw=2 et :