Skip to content

Instantly share code, notes, and snippets.

@jdsumsion
Created January 10, 2012 15:39
Show Gist options
  • Save jdsumsion/1589675 to your computer and use it in GitHub Desktop.
Save jdsumsion/1589675 to your computer and use it in GitHub Desktop.
Commandable example
require 'commandable'
require 'optparse'
class Foo
extend Commandable
# the :default param is optional, and can only be on one method
command "hello", :default
def hello(world="world") # the default value is expressed inline in real ruby
puts "hello #{world.inspect}"
raise_on_invalid_world world
end
def raise_on_invalid_world(world)
raise FriendlyError, world if world =~ /^nowhere/
raise RuntimeError, world if world =~ /^never/
end
# lets me do full commandline parsing in the place the option will be used
command "hello2", :rest
def hello2(*args)
opts = OptionParser.new
options = { world: "world" }
opts.on "-w WORLD", "--world WORLD" do |world|
options[:world] = world
end
opts.order! args
puts "hello2 #{options[:world].inspect}, args: #{args.inspect}"
raise_on_invalid_world options[:world]
end
end
class FriendlyError < RuntimeError
def friendly_name
"bogus place, #{message}"
end
end
Commandable.color_output = false
Commandable.execute ARGV, silent: true
[08:41:35] ~ ↺ ruby foo.rb
hello "world"
[08:41:39] ~ ↺ ruby foo.rb hello
hello "world"
[08:41:41] ~ ↺ ruby foo.rb hello world2
hello "world2"
[08:41:43] ~ ↺ ruby foo.rb hello nowhere
hello "nowhere"
Error: bogus place, nowhere
nowhere
Usage:
Command Parameters Description
hello [world="world"] : hello (default)
hello2 *args : hello2
help : you're looking at it now
[08:41:56] ~ ↺ ruby foo.rb hello never
hello "never"
#<RuntimeError: never>
foo.rb:16:in `raise_on_invalid_world'
foo.rb:11:in `hello'
/home/sumsionjg/.rbenv/versions/1.9.3-p0/gemsets/gitged-experiments/gems/commandable-0.2.3/lib/commandable/commandable.rb:245:in `block (2 levels) in execution_queue'
...snip...
foo.rb:42:in `<main>'
[08:42:22] ~ ↺ ruby foo.rb hello2 never
hello2 "world", args: ["never"]
[08:42:34] ~ ↺ ruby foo.rb hello2 --world=world2 never
hello2 "world2", args: ["never"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment