dcompiled
dcompiled

Reputation: 4832

Dynamically create chef resource from string

Trying to see how best to call some ruby code dynamically from text within a string.

The following creates a directory with chef:

directory /tmp/test do
  mode "755"
  owner me
  group me
  action :create
end

If the text "directory" was contained in a variable, I would like to use this to call the same code without an expicit if statement. I don't know enough about ruby/chef to do this.

Current approach:

if action == "directory"
  directory /tmp/test do
    ...
  end
end

Desired approach (something to the effect of):

"#{action}" /tmp/test do
  ...
end

Upvotes: 0

Views: 464

Answers (1)

coderanger
coderanger

Reputation: 54249

directory in the Chef DSL is a method call. You can dynamically call methods in Ruby using send. In this case it would look like:

send(action, '/tmp/test') do
  ...
end

This is really not recommended for the most part though, it will rapidly lead to hugely unreadable code and I'm not sure what situation you would have where the ... in there would actually be interchangable. Remember that your code should be readable first, and repeating things is fine if they aren't likely to change that often.

Upvotes: 3

Related Questions