Skip to content

Instantly share code, notes, and snippets.

@tsnow
Created October 19, 2012 17:44
Show Gist options
  • Save tsnow/3919580 to your computer and use it in GitHub Desktop.
Save tsnow/3919580 to your computer and use it in GitHub Desktop.
A Rack-like functionality for OptionParser
module Parsable
def self.included(mod)
class << mod
attr_accessor :child_parser
end
mod.child_parser = NullParsable.new
mod.class_eval do
def child_parser
self.class.child_parser
end
end
end
def parser
self.child_parser.parser
end
def option_parser
end
def apply_parser
option_parser
yield
after_parse
end
def child_parser
end
def parse!(vals=ARGV)
apply_parser do
child_parser.parse!(vals)
end
end
def after_parse
end
class NullParsable
include Parsable
def parser
@parser ||= OptionParser.new
end
def child_parser
parser
end
end
end
class TestOptions
attr_accessor :options
include Parsable
self.child_parser = TestNestedOptions.new #TODO: rewrite to
#rack-like mount
def initialize
self.options = {}
end
def option_parser
self.parser.on('-a') do
options[:a] = 1
end
end
def after_parse
puts "a=#{options[:a]}" if options[:a]
end
end
class TestNestedOptions
attr_accessor :options
include Parsable
def initialize
self.options = {}
end
def option_parser
self.parser.on('-b') do
options[:b] = 2
end
end
def after_parse
puts "b=#{options[:b]}" if options[:b]
end
end
#begin; t=TestOptions.new; t.parse!(ARGV); [t.options,t.child_parser.options]; end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment