Skip to content

Instantly share code, notes, and snippets.

@juliocesar
Created August 14, 2012 02:33
Show Gist options
  • Save juliocesar/3345854 to your computer and use it in GitHub Desktop.
Save juliocesar/3345854 to your computer and use it in GitHub Desktop.
# Simplest (?) console action parsing that doesn't use gems.
# The idea, in a nutshell:
#
# $ mycommand foo
#
# * Calls `foo` or a default method as per the ACTIONS constant (see below).
#
# $ mycommand foo bar
#
# * Calls `foo` with "bar" as a parameter.
#
# For a more complete example, check Shining's `shine` command at
# https://github.com/juliocesar/shining/blob/master/bin/shine
# Tres' is still a work in progress.
# A mapping for methods => <means to call method>. So if the user goes
#
# $ mycommand server
#
# It'll map to the `server` method defined below. Arguments are passed directly
# to the method as they're laid in the console. So:
#
# $ mycommand init blah
#
# Will call the `init` method with "blah" being passed as argument.
ACTIONS = {
:server => %w(server),
:new_at => %w(build)
:init => %w(init start)
}
# Exit with status -2 and print a reason to the console
def bail! reason
puts reason
exit -2
end
# Core method that checks the console input, checks if there's a corresponding
# method in `ACTIONS`, and runs the respective method. Run the `new_at` method
# by default if passed a non-recognised parameter, so when you run
#
# $ mycommand facebook_killer
#
# it'll run `new_at` with "facebook_killer" as a parameter.
def figure_what_to_do!
help_and_exit if ARGV.empty?
if ACTIONS.values.flatten.include? ARGV.first
action = ACTIONS.select { |action, args| args.include? ARGV.first }.flatten.first
send action, *ARGV[1..(ARGV.length - 1)]
else
new_at ARGV.first
end
end
# Prints usage help and exits with status -1.
def help_and_exit!
STDERR.puts <<-HELP
Tres \|/
Usage:
tres new <directory>
Example:
tres new myapp
Other commands:
help shows this menu
version shows the current version of Tres you have installed
HELP
exit -1
end
# Define your own methods here.
def new_at
end
def server
end
def init
end
# Boot it!
figure_what_to_do!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment