Ruby code blocks and Chef

流过昼夜 提交于 2019-11-29 15:53:34

If you come from another language (not Ruby), this syntax might seem very strange. Let's break down things.

When calling a method with parameters, in most cases the parentheses are optional:

  • foo(bar) is equivalent to foo bar
  • foo(bar, baz) is equivalent to foo bar, baz

A Ruby block of code can be wrapped in curly braces ({}) or inside a do..end block and can be passed to a method as its last parameters (but note that there's no comma and if you're using parentheses it goes after them. Some examples:

foo(bar) { # code here }

foo(bar) do
  # code here
end

foo bar do
  # code here
end

foo do
  # code here
end

In some cases, code blocks can receive parameters, but in Chef the resources' blocks never do. Just for reference, the syntax for that is:

foo(bar) do |baz, qux|
  baz + qux
end

Specifically about Chef resources, their syntax is usually:

resource_type(name) do
  attribute1 value1
  attribute2 value2
end

This means that, when you say:

log "a debug string" do
  level :debug
end

you're actually creating a log resource whose name attribute is set to "a debug string". It can later be referred to (in other resources, for example) using log[a debug string].

AFAIK, the name attribute is mandatory for every Chef resource type as it's what makes it unique, and allows you to, among other things, call actions on it after it has been declared.


Side note: The ruby block is usually optional for a Chef resource. If you do something like:

directory "/some/path"

Chef will compile that resource using its default attributes (among which is action :create), and try to create the named directory using those.

The do ... end here is not a usual ruby block statement.

It's a implementation of DSL (Domain Specific Language).

Here's a nice explanation [1]:

there is the concept of an internal DSL, which uses the syntax of an exіsting language, a host language, such as Ruby. The means of the language are used to build constructs resembling a distinct language. The, already mentioned, Rake uses this to make code like this possible:

task :codeGen do        
  # do the code generation      
end

Hope that answer your question.

[1] : http://www.infoq.com/news/2007/06/dsl-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!