Organize code in Chef: libraries, classes and resources
- by ColOfAbRiX
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.