ironsand
ironsand

Reputation: 15151

Can't use helper method in Chef

I want to use a method in a recipe, so I create a helper method for it.

my_cookbook/libraries/foo_helper.rb

module Foo
  module Helper
    def foo_daemon_command(action)
      %Q{bash -c "export PATH='/usr/local/bin:/opt/rbenv/bin:$PATH'; eval '$(rbenv init -)'; cd /opt/foo; /opt/rbenv/shims/ruby foo_daemon.rb #{action} >>/var/log/foo/cron_#{action}.log 2>>/var/log/foo/cron_#{action}.log" }
    end
  end
end

And load the method from the recipe.

my_cookbook/recipes/default.rb

Chef::Resource::User.send(:include, Foo::Helper)

execute "foo daemon restart" do
  command foo_daemon_command("restart")
end

When I apply the recipe, I get undefined method error like this:

NoMethodError
-------------
undefined method `foo_daemon_command' for Chef::Resource::Execute

What am I doing wrong?

Upvotes: 4

Views: 2893

Answers (1)

coderanger
coderanger

Reputation: 54211

The specific error is you are patching a function in to the User resource instead of Execute. But the better way to do this would be to mix it in to the current recipe. Just add extend Foo::Helper to the top of the recipe. You could also make it a module method and call it directly as Foo::Helper.foo_daemon_command. In general making global DSL changes should be done with great care and never from recipe code.

Upvotes: 3

Related Questions