Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# The latch function remembers what it was called with
# and returns what it was previously called with.
#
# This is using global namespace - in your code use a module namespace
#
Puppet::Functions.create_function(:latch) do
dispatch :example do
repeated_param 'Any', :arg
end
def example(*args)
adapter = adapterclass.adapt(closure_scope().compiler)
result = adapter.thing
adapter.thing = args
result
end
def adapterclass
@adapterclass ||= Class.new(Puppet::Pops::Adaptable::Adapter) do
attr_accessor :thing
def self.name()
# This is using global namespace - in your code use a module namespace
"LatchFunctionAdapter"
end
end
@adapterclass
end
end
@hlindberg

This comment has been minimized.

Copy link
Owner Author

@hlindberg hlindberg commented Jan 30, 2020

The above makes the adapter have the lifecycle of the compiler. If it should instead have the lifecycle of the environment change line 12 to be:

    adapter = adapterclass.adapt(closure_scope().environment)

You can try it with something like notice([latch(first), latch(second), latch(third)]) to get it to output the array [undef, "first", "second"] (this works with both lifecycles).

Have not tested the env lifecycle - to do that - have an agent request a catalog from master with a notify { "testlatch": message => "Time was: ${latch(Timestamp())}"} - then do it again a little while later.
The first should have the message "Time was:", and the second compile should have "Time was: ".

The env that is used must not have 0 timeout.

@hlindberg

This comment has been minimized.

Copy link
Owner Author

@hlindberg hlindberg commented Jan 30, 2020

To be safe in general use of the pattern showed in the gist, the name of the class returned by name should actually include the id of the class as well - this because it could exist in a different version in memory in another environment - it will however not be a problem as long as it is being used to adapt to the environment or compiler (as shown in this gist) since any other version of the adapter would be adapted to other instances of the compiler/environment...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment