Method: Puppet::Parser::Functions.newfunction
- Defined in:
- lib/puppet/parser/functions.rb
.newfunction(name, options = {}, &block) ⇒ Hash
Create a new Puppet DSL function.
**The newfunction method provides a public API.**
This method is used both internally inside of Puppet to define parser functions. For example, template() is defined in template.rb using the newfunction method. Third party Puppet modules such as [stdlib](forge.puppetlabs.com/puppetlabs/stdlib) use this method to extend the behavior and functionality of Puppet.
See also [Docs: Custom Functions](puppet.com/docs/puppet/5.5/lang_write_functions_in_puppet.html)
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
# File 'lib/puppet/parser/functions.rb', line 188 def self.newfunction(name, = {}, &block) name = name.intern environment = [:environment] || Puppet.lookup(:current_environment) Puppet.warning _("Overwriting previous definition for function %{name}") % { name: name } if get_function(name, environment) arity = [:arity] || -1 ftype = [:type] || :statement unless ftype == :statement or ftype == :rvalue raise Puppet::DevError, _("Invalid statement type %{type}") % { type: ftype.inspect } end # the block must be installed as a method because it may use "return", # which is not allowed from procs. real_fname = "real_function_#{name}" environment_module(environment).send(:define_method, real_fname, &block) fname = "function_#{name}" env_module = environment_module(environment) env_module.send(:define_method, fname) do |*args| Puppet::Util::Profiler.profile(_("Called %{name}") % { name: name }, [:functions, name]) do if args[0].is_a? Array if arity >= 0 and args[0].size != arity raise ArgumentError, _("%{name}(): Wrong number of arguments given (%{arg_count} for %{arity})") % { name: name, arg_count: args[0].size, arity: arity } elsif arity < 0 and args[0].size < (arity + 1).abs raise ArgumentError, _("%{name}(): Wrong number of arguments given (%{arg_count} for minimum %{min_arg_count})") % { name: name, arg_count: args[0].size, min_arg_count: (arity + 1).abs } end r = Puppet::Pops::Evaluator::Runtime3FunctionArgumentConverter.convert_return(send(real_fname, args[0])) # avoid leaking aribtrary value if not being an rvalue function [:type] == :rvalue ? r : nil else raise ArgumentError, _("custom functions must be called with a single array that contains the arguments. For example, function_example([1]) instead of function_example(1)") end end end func = { :arity => arity, :type => ftype, :name => fname } func[:doc] = [:doc] if [:doc] env_module.add_function_info(name, func) func end |