File: camelcase.rb

package info (click to toggle)
puppet-agent 8.10.0-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 27,404 kB
  • sloc: ruby: 286,820; sh: 492; xml: 116; makefile: 88; cs: 68
file content (63 lines) | stat: -rw-r--r-- 2,068 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
54
55
56
57
58
59
60
61
62
63
# frozen_string_literal: true

# Creates a Camel Case version of a String
#
# This function is compatible with the stdlib function with the same name.
#
# The function does the following:
# * For a `String` the conversion replaces all combinations of `*_<char>*` with an upcased version of the
#   character following the _.  This is done using Ruby system locale which handles some, but not all
#   special international up-casing rules (for example German double-s ß is upcased to "Ss").
# * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is capitalized and the conversion is not recursive.
# * If the value is `Numeric` it is simply returned (this is for backwards compatibility).
# * An error is raised for all other data types.
# * The result will not contain any underscore characters.
#
# Please note: This function relies directly on Ruby's String implementation and as such may not be entirely UTF8 compatible.
# To ensure best compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085.
#
# @example Camelcase a String
# ```puppet
# 'hello_friend'.camelcase()
# camelcase('hello_friend')
# ```
# Would both result in `"HelloFriend"`
#
# @example Camelcase of strings in an Array
# ```puppet
# ['abc_def', 'bcd_xyz'].camelcase()
# camelcase(['abc_def', 'bcd_xyz'])
# ```
# Would both result in `['AbcDef', 'BcdXyz']`
#
Puppet::Functions.create_function(:camelcase) do
  dispatch :on_numeric do
    param 'Numeric', :arg
  end

  dispatch :on_string do
    param 'String', :arg
  end

  dispatch :on_iterable do
    param 'Iterable[Variant[String, Numeric]]', :arg
  end

  # unit function - since the old implementation skipped Numeric values
  def on_numeric(n)
    n
  end

  def on_string(s)
    s.split('_').map(&:capitalize).join('')
  end

  def on_iterable(a)
    a.map { |x| do_camelcase(x) }
  end

  def do_camelcase(x)
    # x can only be a String or Numeric because type constraints have been automatically applied
    x.is_a?(String) ? on_string(x) : x
  end
end