-
Notifications
You must be signed in to change notification settings - Fork 8
Using Exiting Methods
To invoke an explicit exit, use one of the exiting methods:
- exit!
- error!
- help!
- version!
The exit! method is a general way to invoke an explicit exit.
Without arguments, exit! simply exits the command. The exit code is set to 0.
class Mytrue < Cli::Command
def run
exit!
end
end
Mytrue.run
Output:
$ mytrue
$ echo $?
0
If the error option is true, the exit code is set to 1.
class Myfalse < Cli::Command
def run
exit! error: true
end
end
Myfalse.run
Output:
$ myfalse
$ echo $?
1
You can specify the exit code.
class Myfalse < Cli::Command
def run
exit! code: 1
end
end
You can specify a message text that is printed before a command exits.
class Bye < Cli::Command
def run
exit! message: "bye :)"
end
end
Or simply:
class Bye < Cli::Command
def run
exit! "bye :)"
end
end
If a specified exit code is other than 0, the message is printed to STDERR.
class DontSayGoodbye < Cli::Command
class Options
arg "greeting"
end
def run
if /bye/ =~ args.greeting
exit! ":(", error: true # to STDERR
else
exit! ":)" # to STDOUT
end
end
end
If the help option is true, the command's help message will be printed.
class HelpOrNothing < Cli::Command
class Options
bool "-h", desc: "show this help"
end
def run
exit! help: options.h?
end
end
HelpOrNothing.run ARGV
Output:
$ help-or-nothing -h
help-or-nothing [OPTIONS]
Options:
-h show this help
If the message argument is specified, both the specified message and the help message will be printed.
class TheFriday < Cli::Command
class Help
header <<-EOS
Don't execute it on Friday the 13th.
EOS
end
def the_friday?
Time.now.day == 13 && Time.now.friday?
end
def run
exit! "YOU DO IT!!!", help: true, error: true if the_friday?
end
end
STDERR may be written:
YOU DO IT!!!
the-friday
Don't execute it on Friday the 13th.
exit! internally calls the standard exit
method. So you can make a combination of exit! and at_exit
handlers.
class FinallySmile < Cli::Command
def run
puts ":("
exit!
end
end
at_exit { puts ":)" }
FinallySmile.run
Output:
$ finally-smile
:(
:)
The error! method is similar to exit!, however the error option is true as default.
These lines are equivalent:
exit! error: true
exit! code: 1
error!
error! code: 1
The help! method is similar to exit!, however the help option is true as default.
If the message argument is specified, the error option is true as default. So,
help! "See help!"
is equivalent to
exit! "See help!", help: true, error: true
not
exit! "See help!", help: true
The version! method prints the command's version and exits. The exit code is 0.
class VersionOrNothing < Cli::Command
version "1.0.0"
class Options
bool "-v"
end
def run
version! if options.v?
end
end
Output:
$ version-or-nothing -v
1.0.0