For the most part, implementation methods are normal Ruby. However, there are some special features available for accessing Puppet variables, working with provided blocks of Puppet code, and calling other functions.
Accessing Puppet variables
We recommend that most functions only use the arguments they are passed. However, you also have the option of accessing globally-reachable Puppet variables. The main use case for this is accessing facts, trusted data, or server data.
closure_scope
method, which takes
no arguments and returns a Puppet::Parser::Scope
object.Use #[](varname)
to call on a scope object,
which returns the value of the specified variable. Make sure to exclude the $
from the variable name. For
example:
Puppet::Functions.create_function(:'mymodule::fqdn_rand') do
dispatch :fqdn do
# no arguments
end
def fqdn()
scope = closure_scope
fqdn = scope['facts']['networking']['fqdn']
# ...
end
end
Working with lambdas (code blocks)
Convention | Description |
---|---|
block_given?
|
If your signature specified an optional code block, your
implementation method can check for its presence with the |
yield()
|
When you know a block was provided, you can execute it any
number of times with the The arguments to |
Proc
by specifying an extra argument with an ampersand (&
) flag. This works the same
way as capturing a Ruby block as a Proc
. After you capture the block, you can execute
it with #call
instead of
yield
. You can also use
any other Proc
instance
methods to examine
it.def implementation(arg1, arg2, *splat_arg, &block)
# Now the `block` variable has the provided lambda, as a Proc.
block.call(arg1, arg2, splat_arg)
end
Calling other functions
If you want to call another Puppet function (like include
) from inside a function, use the special call_function(name, *args, &block)
method.
# Flatten an array of arrays of strings, then pass it to include:
def include_nested(array_of_arrays)
call_function('include', *array_of_arrays.flatten)
end
The first argument must be the name of the function to call, as a string.
The next arguments can be any data type that the called function accepts. They are passed as arguments to the called function.
- The last argument can be a Ruby
Proc
, or a Puppet lambda previously captured as aProc
. You can also provide a block of Ruby code using the normal block syntax.def my_function1(a, b, &block) # passing given Proc call_function('my_other_function', a, b, &block) end def my_function2(a, b) # using a Ruby block call_function('my_other_function', a, b) { |x| ... } end
Related topics:
Proc
,
yield
,
block_given?
,
Puppet variables, Lambdas, Facts and built-in variables.