Organize code in Chef: libraries, classes and resources

cheflibrariesresourcesruby

I am new to both Chef and Ruby and I am implementing some scripts to learn them. Now I am facing the problem of how to organize my code: I have created a class in the library directory and I have used a custom namespace to maintain order. This is a simplified example of my file:

# ~/chef-repo/cookbooks/mytest/libraries/MyTools.rb
module Chef::Recipe::EP
    class  MyTools
        def self.print_something( text )
            puts "This is my text: #{text}"
        end
        def self.copy_file( dir, file )
            cookbook_file "#{dir}/#{file}" do source "#{dir}/#{file}" end
        end
    end
end

From my recipe I call both methods:

# ~/chef-repo/cookbooks/mytest/recipes/default.rb
EP::MyTools.print_something "Hello World!"
EP::MyTools.copy_file "/etc", "passwd"

print_something works fine, but with copy_file I get this error:

undefined method `cookbook_file' for Chef::Recipe::EP::FileTools:Class

It's clear to me that I don't know how to create libraries in Chef or I don't know some basic assumptions.
Can anyone help me, please? I am looking for a solution of this problem (organize my code, libraries, use resources in classes) or, better, a good Chef documentation as I find the documentation very deficient in clarity and disorganized so that research through it is a pain.

Best Answer

The error message means that there is no cookbook_file method in your class. Module names don't imply Class inheritance, they merely provide isolated namespaces. If you want access to the Chef methods you need to subclass the appropriate Chef class. Learning both Ruby and Chef is a lot to swallow in one go. Writing an effective library will take some time and for the most part shouldn't be required.

Workflow in Chef is not yet standardized. There are a bunch of different approaches still competing for best practice.

However, I would suggest you start with Berkshelf. It will build a basic cookbook structure for you.

http://berkshelf.com/

Tutorial for berkshelf ( can't post real url due to limitations )

misheska.com/blog/2013/06/16/getting-started-writing-chef-cookbooks-the-berkshelf-way/

The chef documentation is in the process of being cleaned up. There are some old rather incomplete docs out there and it's hard to know what's current. Most current effort is going into this site:

https://learnchef.opscode.com/