diff --git a/lib/puppet/functions/to_python.rb b/lib/puppet/functions/to_python.rb new file mode 100644 index 0000000..c8d1468 --- /dev/null +++ b/lib/puppet/functions/to_python.rb @@ -0,0 +1,37 @@ +# frozen_string_literal: true + +# @summary +# Convert an object into a String containing its Python representation +# +# @example how to output Python +# # output Python to a file +# $listen = '0.0.0.0' +# $port = 8000 +# file { '/opt/acme/etc/settings.py': +# content => inline_epp(@("SETTINGS")), +# LISTEN = <%= $listen.to_python %> +# PORT = <%= $mailserver.to_python %> +# | SETTINGS +# } + +Puppet::Functions.create_function(:to_python) do + dispatch :to_python do + param 'Any', :object + end + + # @param object + # The object to be converted + # + # @return [String] + # The String representation of the object + def to_python(object) + case object + when true then 'True' + when false then 'False' + when :undef then 'None' + when Array then "[#{object.map { |x| to_python(x) }.join(', ')}]" + when Hash then "{#{object.map { |k, v| "#{to_python(k)}: #{to_python(v)}" }.join(', ')}}" + else object.inspect + end + end +end diff --git a/spec/functions/to_python_spec.rb b/spec/functions/to_python_spec.rb new file mode 100644 index 0000000..17c7ca7 --- /dev/null +++ b/spec/functions/to_python_spec.rb @@ -0,0 +1,27 @@ +# frozen_string_literal: true + +require 'spec_helper' + +describe 'to_python' do + it { is_expected.not_to eq(nil) } + it { is_expected.to run.with_params('').and_return('""') } + it { is_expected.to run.with_params(:undef).and_return('None') } + it { is_expected.to run.with_params(true).and_return('True') } + it { is_expected.to run.with_params(false).and_return('False') } + it { is_expected.to run.with_params('one').and_return('"one"') } + it { is_expected.to run.with_params(42).and_return('42') } + it { is_expected.to run.with_params([]).and_return('[]') } + it { is_expected.to run.with_params(['one']).and_return('["one"]') } + it { is_expected.to run.with_params(['one', 'two']).and_return('["one", "two"]') } + it { is_expected.to run.with_params({}).and_return('{}') } + it { is_expected.to run.with_params('key' => 'value').and_return('{"key": "value"}') } + it { + is_expected.to run.with_params('one' => { 'oneA' => 'A', 'oneB' => { 'oneB1' => '1', 'oneB2' => '2' } }, 'two' => ['twoA', 'twoB']) + .and_return('{"one": {"oneA": "A", "oneB": {"oneB1": "1", "oneB2": "2"}}, "two": ["twoA", "twoB"]}') + } + + it { is_expected.to run.with_params('‰').and_return('"‰"') } + it { is_expected.to run.with_params('竹').and_return('"竹"') } + it { is_expected.to run.with_params('Ü').and_return('"Ü"') } + it { is_expected.to run.with_params('∇').and_return('"∇"') } +end