Function best approach

20 views
Skip to first unread message

Peter Berghold

unread,
Jul 19, 2016, 12:50:45 PM7/19/16
to puppet-users
Let me preface everything I'm about to say by saying I only started seriously coding in Ruby about a year ago.  I've been a Perl guy since 1989  and C/C++ and friends for longer than that so I'm not a total newbie.  The question I'm going to ask notwithstanding. :-)

What I'm trying to accomplish is writing a function that will parse text data that will be used as part of a fact, in a custom function for Puppet and several other places within the Puppet ecosphere. 

I've got the parser itself written but I'd hate to think I have to duplicate that code everywhere it's needed.  What would be the best approach to making the subroutine available to a custom fact, custom function and type/provider all at once?

A synopsis of sorts.  The custom fact generates an aggregate fact and the custom function and custom type/provider compare a parameter fed to a class to that value to make a logic decision. 

Ideas?

Thomas Müller

unread,
Aug 9, 2016, 9:52:52 AM8/9/16
to Puppet Users
I suspect you would need to create a rubygem and deploy it on all machines? but maybe this is more a question for the Puppet Developers mailinglist.

- Thomas 

Jeff McCune

unread,
Aug 9, 2016, 10:16:42 AM8/9/16
to puppet...@googlegroups.com
On Aug 9, 2016, at 9:52 AM, Thomas Müller <tho...@chaschperli.ch> wrote:

What would be the best approach to making the subroutine available to a custom fact, custom function and type/provider all at once?

I’d start by looking at using a standard puppet module.  If you place the subroutine (a.k.a “method” in Ruby parlance) into a ruby module (different than a puppet module), you could then reuse the method in a custom fact, external fact, function and type & provider.  Taking this approach also has the benefit of letting Puppet deal with the distribution of the code for you using the plugignsync mechanism.

The reusable method could go into lib/puppet_x/my_name/my_stuff.rb as module PuppetX::MyName::MyThing; def my_method; end; end; end  You could then use include PuppetX::MyName::MyThing in your various implementations.

The convention with PuppetX is to place your re-usable utility code under a module named after you or your organization to avoid namespace conflicts with other published modules.  “MyStuff” could be a class or a module depending on what you’re accomplishing.

I recommend starting with defining “MyThing” as a class, then instantiating it where you need it.  Ruby also allows methods to be composed via the include or extend statements, but I recommend avoiding that functionality unless a standard class doesn’t fit your needs for some reason.  Include and extend can be more difficult to test, less clear to a reader, and less intuitive generally speaking than a standard class is.

Hope this helps,
Jeff McCune
Principal Consultant & Founder
Reply all
Reply to author
Forward
0 new messages