Last Updated: February 25, 2016
·
2.149K
· jessedearing

Use Ruby arrays for repetitive resource declaration

In a Chef recipe you can use a Ruby array to make declaring multiple resources with the same attributes.

For example, this:

directory "/foo/bar" do
  owner 'foo'
end

directory "/baz/bat" do
  owner 'foo'
end

directory "/blah" do
  owner 'foo'
end

Can be changed to this:

["/foo/bar",
 "/baz/bat",
 "/blah"].each do |dir|
  directory dir do
    owner 'foo'
  end
end

3 Responses
Add your response

This gives me even more incentive to learn more Ruby and put this into practice.

over 1 year ago ·

To keep your array definition tidier and avoid odd spacing, you might go for something like this:

%w[/foo/bar /baz/bat /blah].each { |dir| directory dir }

If you need to specify attributes, using the longer block syntax is preferred:

%w[/foo/bar /baz/bat /blah].each do |dir|
    directory dir do
        owner 'foo'
    end
}
over 1 year ago ·

Intuitive, elegant, and fun to write. Things like this are why I love Ruby so much.

over 1 year ago ·