Skip to content

Using Exiting Methods

mosop edited this page Dec 10, 2016 · 23 revisions

To invoke an explicit exit, use one of the exiting methods:

  • exit!
  • error!
  • help!
  • version!

exit!

The exit! method is a general way to invoke an explicit exit.

Without Arguments

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

With at_exit Handlers

exit! internally calls the standard exit method. So, you can make a combination with at_exit handlers.

class FinallySmile < Cli::Command
  def run
    puts ":("
    exit!
  end
end

at_exit { puts ":)" }

FinallySmile.run

Output:

$ finally-smile
:(
:)

With an Exit Code

You can specify the exit code.

class Myfalse < Cli::Command
  def run
    exit! code: 1
  end
end

Myfalse.run

With a Message

You can specify a message that is printed before a command exits.

class Bye < Cli::Command
  def run
    exit! message: "bye :)" # or simply 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
    string "greeting"
  end

  def run
    if /bye/ =~ options.greeting
      exit! ":(", code: 1 # STDERR
    else
      exit! ":)" # STDOUT
    end
  end
end

help!

class Command < Cli::Command
  def run
    help!
  end
end

Command.run # => 0

This command just ends after printing its help message. Command.run returns 0.

To print a message to STDERR and exit with an error code, use :error option.

help! error: true

If the :error option is true, run method returns 1. To specify a number, use the :code option.

help! code: 22

You can also let a command exit with an additional message:

help! message: "You passed an illegal option! See help!"

Or simply:

help! "You passed an illegal option! See help!"

Calling help! with the :message argument implies that the :error option is true. To exit normally, set false to :error.

exit! and error!

exit! is more general purpose than help!.

class Command < Cli::Command
  def run
    exit!
  end
end

Command.run # => 0

It just ends and returns 0 without a message.

To print a message:

exit! "bye."

Or more variations:

exit! help: true # equivalent to help!
exit! error: true # returns 1 as an exit code
exit! "message", error: true, help: true # equivalent to help!("message")

error! is similar to exit!, but the :error option is true as default.

error! # ends with 1 as an exit code
error! "message" # equivalent to exit!("message", error: true)
error! code: 22 # specifies exit code
error! help: true # equivalent to help!(error: true)
error! "message", help: true # equivalent to help!("message")

Clone this wiki locally