Override #run to add exception handling?

91 views
Skip to first unread message

StormSilver

unread,
Dec 2, 2008, 2:39:18 PM12/2/08
to Capistrano
Hi all,

I would like to override
Capistrano::Configuration::Actions::Invocation#run to add a little
exception handling, namely, to ask if the user would like to continue
anyway. Like so:

def run_with_error_handling(*args, &block)
begin
run_without_error_handling(*args, &block)
rescue Capistrano::CommandError => e
say("#{e}")
continue = confirm("The command failed. Do you want to continue
anyway?")
if (!continue)
bail("Command failed.")
end
end
end

Simple, right? But I can't figure out how to set up the method chain
the right way. Seems like whatever I do, ruby complains that:

`alias_method': undefined method `run' for class `#<Class:
0x126c98c>::Capistrano::Configuration' (NameError)

Huh! I have tried creating a new module with the method and aliases
and including it in Capistrano::Configuration, and I have tried
opening the Capistrano::Configuration::Actions::Invocation module and
adding my aliases there.

Here is what I'm doing:

alias_method(:run_without_error_handling, :run) unless method_defined?
(:run_without_error_handling)
alias_method(:run, :run_with_error_handling)

Can anyone shed a little light on this?

Thanks,
-- Eric

Jamis Buck

unread,
Dec 2, 2008, 3:08:16 PM12/2/08
to capis...@googlegroups.com
If you're doing your own module, you need to do the aliasing in the
included() method of the module:

module MyModule
def self.included(base)
base.send(:alias_method, :run_without_error_handling, :run)
base.send(:alias_method, :run, :run_with_error_handling)
end

def run_with_error_handling(...)
...
end
end

Capistrano::Configuration.send(:include, MyModule)

If you try to alias in the body of the module, then you'll get
complaints that the run method doesn't exist. And you'll also need to
make sure you are including your module after the Invocation module is
included.

- Jamis
Reply all
Reply to author
Forward
0 new messages