I have been using Chef for about 4 years and I know a lot has changed or maybe I really fulling understood/grok'ed this particular subject.
I need a little help understanding Chef libraries and where method
definitions are held in the class tree. I am trying to teach some of my
colleges about libraries and custom resources and found that I could not
answer the questions I pose below.
In the past I have always written libaries one of two ways
###########
# way one #
###########
module Foo
module Bar
def my_method
true
end
end
end
Chef::Recipe.send(:include, ::Foo::Bar)
Chef::Resource.send(:include, ::Foo::Bar)
Chef::Provider.send(:include, ::Foo::Bar)
Now in any Chef recipe I can use my_method without any class prefixing (just call my_method)
I know this is some what or very much discouraged as monkey patching
your own method names into the "official" class space is likely to do harm
when your name overwrites a previously existing method
###########
# way two #
###########
From Customizing Chef (Cowie) -- I also have been using this format
class Chef::Recipe
class Company
def self.my_method
true
end
end
end
Now in any Chef recipe I can use Chef::Recipe::Company.my_method() or Company.my_method()
This puts all of my methods in a custom namespace which prevents
conflicts. The only very small issue is that I have to prefix the calls
with their container class.
################
# Question One #
################
I have never bothered to ask this but now I will. In the discouraged paradigm of including my custom methods in 3 namspace classs
Chef::Recipe.send(:include, ::Foo::Bar)
Chef::Resource.send(:include, ::Foo::Bar)
Chef::Provider.send(:include, ::Foo::Bar)
I get whey have to beincluded into Chef::Recipe -- what is the need for the include into Chef::Resource and Chef::Provider?
################
# My Confusion #
################
I was recently looking at some of the Chef maintained community
cookbooks and came across a lot of library files that had plain old
method definitions such as:
def my_method
true
end
And then these were used in Recipes with their bare names, as if they had just been automatically include into Chef::Recipe.
################
# Question Two #
################
When you define a method in a library file that does not have an defined outer class or module:
(1) Which class do these methods live in?
(2) Can they be used across cookbooks
(3) Can you do damaging things with this seeming monkey patching by
simply defining a method in a library file that overwrites and existing
method.
If there is any good articles that explain this please just point me there. Thanks