Skip to content
Dave Copeland edited this page Nov 27, 2010 · 12 revisions

Hooks

GLI provides three basic hooks for running code at different parts of your application's lifecycle.

Pre Hook

The pre hook is useful for setting up global data that most or all of your commands will need. For example, if your application interacts with a remote web service, the pre hook might use global options to establish a connection to the web service, and provide a global variable representing that connection to whichever command is actually requested by the user.

Once the command line arguments are parsed, the pre hook, if included, will be called. It's given the global options, the command the user issued, the command-specific options, and the arguments list.

pre do |global_options,command,options,args|
  # Set up here
  # the block should evaluate to true or false
end

If the block evaluates to false, the program will stop and the command requested will not be executed.

Post Hook

The post hook is called after your command runs, assuming there has been no error. The post hook is given the same arguments as the pre hook. This is useful if you need to close any open resources your application might've opened up or do any other genreal cleanup.

post do |global_options,command,options,args|
  # Cleanup code here
end

Error Hook

Your commands should simply raise exceptions if anything went wrong and you wish to halt program execution. The Error hook is called in these cases. The error hook is also called at any other part of the application lifecycle, so the parsed command line options may not be available. All that is given to the block is the exception that triggered the error:

on_error do |ex|
  # evaluate to true or false
end

If the block evaluates to true, GLI's normal error handling will occur. This currently amounts to printing the exception's message to the standard error. If the block evalulates to false, GLI will do nothing before exiting the program. This gives you some flexibility on what you want to do when there's an error.

Clone this wiki locally