Skip to content

Instantly share code, notes, and snippets.

@theo-bittencourt
Last active November 19, 2016 05:40
Show Gist options
  • Save theo-bittencourt/ebed78011a4435362daf7c61aec205f4 to your computer and use it in GitHub Desktop.
Save theo-bittencourt/ebed78011a4435362daf7c61aec205f4 to your computer and use it in GitHub Desktop.
Snippet to build Ruby command line executables
#!/usr/bin/env ruby
# Snippet to build command line executables like this:
# ./my_script command --opt-a "opt A"
require 'optparse'
require 'singleton'
require 'pry'
class Command
attr_accessor :options
def initialize options
@options = options
end
def perform cmd
respond_to?(cmd.to_s) ? public_send(cmd) : raise('cmd no found')
end
# Commands go here. Define it as public methods
# def cmd
# puts "call cmd_1 on options #{options.inspect}"
# end
end
class CommandOptions
include Singleton
attr_accessor :options, :options_parser
def parse!
self.options = {}
self.options_parser = OptionParser.new do |opt|
# Executable instructions go here
# opt.banner = "Usage: my_script COMMAND [OPTIONS]"
# opt.separator ""
# opt.separator "Commands"
# opt.separator " cmd_1: run cmd_1 with required param"
# opt.separator " cmd_2: run cmd_2 with coerced param"
# opt.separator ""
# opt.separator "Options"
# opt.on('-d','--common-no-param', 'param to run cmd') do |common_no_param|
# options[:common_no_param] = common_no_param
# end
# opt.on('-d','--common-param param', 'param to run cmd') do |common_param|
# options[:common_param] = common_param
# end
# opt.on('-e','--environment ENVIRONMENT', 'required param to run cmd') do |environment|
# options[:environment] = environment
# end
# opt.on('-c','--corced-opt [OPT_ARRAY]', Array, 'required param to run cmd') do |corced_opt|
# options[:opt_array] = corced_opt
# end
opt.on('-h','--help', 'help') do
puts options_parser
end
end
options_parser.parse!
end
end
begin
CommandOptions.instance.parse!
Command.new(CommandOptions.instance.options).perform(ARGV[0])
rescue => e
e.to_s == 'cmd no found' ? puts(CommandOptions.instance.options_parser) : raise
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment