0

I have a chef recipe name my_recipe and I would like to add a library to it to assist me in getting some stuff done, while still being able to run chefspec smoothly. I read the extend recipe documentation, but couldn't find how to extends (or dynamically create) a class within the recipe namespace.

here is a snippet:

# my_cookbook/recipes/my_recipe.rb
foo = MyRecipe::MyClass.foo


# my_cookbook/libraries/my_class.rb
class Chef
  class Recipe
    class MyRecipe
      unless defined?(Chef::Recipe::MyRecipe::MyClass)
        class MyClass
          def self.foo
            # do stuff
          end
        end
      end
    end
  end
end

what am I missing? how chef translate a dsl recipe name my_recipe to a recipe object (MyRecipe)?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Mr.
  • 9,429
  • 13
  • 58
  • 82

1 Answers1

0

There is no such translation. I don't really understand where you got this whole class structure for. What you want is just:

module MyHelpers
  def self.foo

And then MyHelpers.foo in your recipe.

coderanger
  • 52,400
  • 4
  • 52
  • 75
  • that does not work for me, as it can cause many collision if someone else has introduces the same module name within his\her development. to eliminate such a collision, i wanted to use the recipe namespace. with that being said, i remember doing so many years ago. yet, i saw [this post](https://stackoverflow.com/questions/23056576/how-to-extend-chef-resource), just couldn't get how chef translate the dsl to corresponding object, so i could use this object to mixin\trait my libraries\helpers. – Mr. May 06 '18 at 07:57
  • Defining custom resources is very different from defining non-resource helper methods. Do not monkey-patch modules under `Chef::Recipe` like that. Not not, now ever :) There is no more or less risk of name collision if you just use your own namespace. – coderanger May 07 '18 at 06:35