Information Technology Reference
In-Depth Information
search_query
Apache Solr search query.
Make sure
recipes/default.rb
matches the code contained in
Example 12-2
.
It contains Chef
code that queries Chef Server for all items in the
users
data bag.
Example 12-2. chefdk/chef-playground/cookbooks/nodes/recipes/default.rb
#
# Cookbook Name:: users
# Recipe:: default
#
# Copyright (C) 2014
#
#
#
# Print every node name matching the search pattern
search
(
"node"
,
"*:*"
)
.
each
ddo
|
matching_node
|
log matching_node
.
to_s
end
end
The
.each
statement in
recipes/default.rb
is a looping construct specific to Ruby. If you are
familiar with other programming languages, look at the following code for something that
might be a little more familiar. The following code creates a
counter
variable, incrementing
it by 1 until it equals 5:
counter
=
0
while
while
counter
<
5
puts
counter
counter
=
counter
+
1
end
end
Although the preceding is completely valid Ruby, a more idiomatic way is to use the
.each
iterator to return all the elements in an array one-by-one. Ruby shines in having really com-
pact ways to specify common coding constructs.
The
do..end
block construct is more sophisticated than we've covered so far. It can be used
to define a method with no name. Also, you can pass this nameless method one or more
parameters enclosed by two vertical bars (||), such as
|counter|
in the following example.