sprintf_hash.rb 1.1 KB

1234567891011121314151617181920212223242526272829
  1. # Uses sprintf with named references.
  2. #
  3. # The first parameter is format string describing how the rest of the parameters in the hash
  4. # should be formatted. See the documentation for the `Kernel::sprintf` function in Ruby for
  5. # all the details.
  6. #
  7. # In the given argument hash with parameters, all keys are converted to symbols so they work
  8. # with the `sprintf` function.
  9. #
  10. # @example Format a string and number
  11. # $output = sprintf_hash('String: %<foo>s / number converted to binary: %<number>b',
  12. # { 'foo' => 'a string', 'number' => 5 })
  13. # # $output = 'String: a string / number converted to binary: 101'
  14. #
  15. Puppet::Functions.create_function(:sprintf_hash) do
  16. # @param format The format to use.
  17. # @param arguments Hash with parameters.
  18. # @return The formatted string.
  19. dispatch :sprintf_hash do
  20. param 'String', :format
  21. param 'Hash', :arguments
  22. # Disabled for now. This gives issues on puppet 4.7.1.
  23. # return_type 'String'
  24. end
  25. def sprintf_hash(format, arguments)
  26. Kernel.sprintf(format, Hash[arguments.map { |(k, v)| [k.to_sym, v] }])
  27. end
  28. end