简体   繁体   中英

Unable to figure out ruby method “directory” and what it does

I am very new to ruby and was trying to understand some code when I got stuck at this snippet:

directory "test_dir" do
    action :create
    recursive true
end

I tried googling directory class but was unsuccessful. I found a class Dir but its not the same. I see that intuitively this snippet should create a new directory and name it test_dir but I do not want to assume things and move forward.

EDIT This was a part of a chef-recipe which is used to launch a particular task. For the purposes of launching, it needs to create a directory and download some jars to it. There is an execute method below which goes like this:

execute 'deploy' do
    action :nothing
    # ignore exit status of storm kill command
    command <<-EOH
      set -e
      storm kill #{name} -w 1 || true
      sleep 3
      storm jar #{points to the jar}
    EOH
end

Sorry I have to be a bit obfuscated as some of the things are not open sourced.

It's the Chef internal DSL for Directory management. Read more here: http://wiki.opscode.com/display/chef/Resources#Resources-Directory

PS: The recursive true tells it to create the folder much like mkdir -p .

directory is not a class, it is a method. I do not know what module it is a part of, but that snippet is about equivalent to this:

Kernel.directory.call("test_dir",lambda {action :create; recursive true})

That snippet uses some gem that adds a directory method to the Kernel object.

As others have mentioned, it is part of the directory management DSL Chef . A DSL is a set of methods integrated into the Kernel object; because of the very flexible method calling syntax of Ruby, method calls can look a lot like language keywords. That makes task specific commands (Domain Specific Languages: DSL) look very nice in Ruby; easy to use and flexible. Thus gems that add DSLs are very common.

It is the Directory resource of the Chef framework. (DSL stands for domain-specific language. Ruby is well suited for them.)

The snippet you pasted is not really enough information to go on (need context; where is the snippet from?)

That said directory looks more like a method than a class. First, it's lowercased and classes are CamelCased.

If it's a method, it's defined somewhere within the application. Have you tried something like this:

grep -r "def directory" ./ or

grep -r "directory" ./| grep "def"

If not in the application itself, it would be defined in one of the application's dependencies ( grep -r "..." $GEM_HOME/gems instead)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM