Skip to content

Commit

Permalink
added response dispatching again. (much simpler this time)
Browse files Browse the repository at this point in the history
  • Loading branch information
joshbuddy committed Aug 29, 2010
1 parent e5ca6e9 commit de53c35
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
25 changes: 25 additions & 0 deletions README.rdoc
Original file line number Diff line number Diff line change
Expand Up @@ -232,3 +232,28 @@ If you try parsing invalid parameters, you can get back friendly error messages
=> ["File is required"]
@parser.parse(%w(kill --pid=something)).error_messages
=> ["Pid is invalid"]

The response from #parse can also be used to dispatch. All that's required is the target object be able to respond to <tt>params=</tt>.

For example

class Runner
attr_accessor :params
def install(file)
puts "I'm installing #{file} with #{params.inspect}"
end
end

parser = Optitron.new {
help
opt 'verbose', "Be very loud"
cmd "install", "This installs things" do
arg "file", "The file to install"
end
}

parser.parse(%w(install this_file -v)).dispatch(Runner.new)

Will output

I'm installing this_file with {"help"=>false, "verbose"=>true}
9 changes: 9 additions & 0 deletions lib/optitron/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,14 @@ def validate
def valid?
@errors.empty?
end

def dispatch(target)
if valid?
target.params = params
target.send(command.to_sym, *args)
else
puts response.error_messages.join("\n")
end
end
end
end
16 changes: 16 additions & 0 deletions spec/dispatch_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
require 'spec_helper'

describe "Optitron::Response dispatch" do
it "should dispatch" do
target = mock('target')
target.should_receive(:params=).with({'verbose' => false})
target.should_receive(:install).with('thefile')
@parser = Optitron.new {
opt 'verbose', "Be very loud"
cmd "install", "This installs things" do
arg "file", "The file to install"
end
}
@parser.parse(%w(install thefile)).dispatch(target)
end
end

0 comments on commit de53c35

Please sign in to comment.