Common code inclusion

asked 2016-09-15 11:25:15 -0500

updated 2016-09-15 12:41:07 -0500

What's the best approach to include code needed at multiple places? I hardly wanna copy 400 lines of code across a dozen files.

I've got a basis defined type my_class::a. I've got several other defined types my_class::b, my_class:c, my_class::d. b,c and d share all the same parameters of a. Their implementation differs by some values. b, c and d all have additional parameters.

define my_class::a (
  # COMMON PARAMETER LIST
) {
  $t = 'a'
  $x = 42
  # IMPLEMENTATION depending on $t and $x (and parameters, of course)
}

 

define my_class::b (
  #INCLUDE COMMON PARAMETERS here
  # additional parameters here
) {
  $t = 'abc'
  $x = 43
  #INCLUDE COMMON THINGS IMPLEMENTATION
  # …
  # some additional things with the additional params (and common parameters)
}

Ideally the inclusion shall be automatically triggered before/while/during catalog compilation. Having to mind to trigger the common code inclusion each time something in it changed, is already bad.

PS: No splat.

PPS: increased difficulty level, some parameter names (of the common parameters set) change across defined types [I really need something like a preprocessor, but it's gotta be triggered automatically]

edit retag flag offensive close merge delete

Comments

1

I would look to providing your parameters as a configuration hash, as opposed to strict static parameters. (see https://forge.puppet.com/KyleAnderson/consul for an example), but that only helps with part of your problem.

DarylW gravatar imageDarylW ( 2016-09-15 12:59:44 -0500 )edit

You can put some of the common code in a module that you include via composition, and you wrap it and 'reach into' it in your other modules. It isn't pretty, but I think it's the closest you can get given your constraints. Perhaps there is a better way to approach the problem?

DarylW gravatar imageDarylW ( 2016-09-15 13:01:33 -0500 )edit

where the names 'change' you just have to do a translation.. $specific_name = config_hash['common_name']

DarylW gravatar imageDarylW ( 2016-09-15 13:03:19 -0500 )edit

I heavily rely on data type checking. A configuration hash is sub-optimal. I want error message to appear, where they make problems. I don't want to split my module. A module is supposed to solve for itself a common problem. I want the parameter names to actually change. Is thr preprocessor for PP?

Kai Burghardt gravatar imageKai Burghardt ( 2016-09-16 16:35:55 -0500 )edit

Yeah, I have no time to wait. I'm doing it by templates now. I've got a module which generates code of the other module. Huargh… Definitely not the best approach (creative though [my self set constraint was: use tools which are already there]).

Kai Burghardt gravatar imageKai Burghardt ( 2016-09-18 09:10:47 -0500 )edit