Skip to content

Instantly share code, notes, and snippets.

@hlindberg
Last active January 30, 2020 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hlindberg/e033ab9c8e20282cc494db6f04afc308 to your computer and use it in GitHub Desktop.
Save hlindberg/e033ab9c8e20282cc494db6f04afc308 to your computer and use it in GitHub Desktop.
# 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
Copy link
Author

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
Copy link
Author

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