Permalink
Browse files

Add with_padding and invoke_with_padding.

  • Loading branch information...
josevalim committed Feb 23, 2010
1 parent 10a08f2 commit e93882af5336c08786d00da578c0f158f65ad7ed
Showing with 34 additions and 18 deletions.
  1. +12 −15 lib/thor/group.rb
  2. +5 −0 lib/thor/invocation.rb
  3. +8 −3 lib/thor/shell.rb
  4. +9 −0 spec/shell_spec.rb
View
@@ -253,22 +253,19 @@ def create_task(meth) #:nodoc:
# Shortcut to invoke with padding and block handling. Use internally by
# invoke and invoke_from_option class methods.
def _invoke_for_class_method(klass, task=nil, *args, &block) #:nodoc:
- shell.padding += 1
-
- result = if block_given?
- case block.arity
- when 3
- block.call(self, klass, task)
- when 2
- block.call(self, klass)
- when 1
- instance_exec(klass, &block)
+ with_padding do
+ if block
+ case block.arity
+ when 3
+ block.call(self, klass, task)
+ when 2
+ block.call(self, klass)
+ when 1
+ instance_exec(klass, &block)
+ end
+ else
+ invoke klass, task, *args
end
- else
- invoke klass, task, *args
end
-
- shell.padding -= 1
- result
end
end
View
@@ -119,6 +119,11 @@ def invoke(name=nil, *args)
end
end
+ # Invokes using shell padding.
+ def invoke_with_padding(*args)
+ with_padding { invoke(*args) }
+ end
+
protected
# Configuration values that are shared between invocations.
View
@@ -45,19 +45,16 @@ def initialize(args=[], options={}, config={})
# Holds the shell for the given Thor instance. If no shell is given,
# it gets a default shell from Thor::Base.shell.
- #
def shell
@shell ||= Thor::Base.shell.new
end
# Sets the shell for this thor class.
- #
def shell=(shell)
@shell = shell
end
# Common methods that are delegated to the shell.
- #
SHELL_DELEGATED_METHODS.each do |method|
module_eval <<-METHOD, __FILE__, __LINE__
def #{method}(*args)
@@ -66,6 +63,14 @@ def #{method}(*args)
METHOD
end
+ # Yields the given block with padding.
+ def with_padding
+ shell.padding += 1
+ yield
+ ensure
+ shell.padding -= 1
+ end
+
protected
# Allow shell to be shared between invocations.
View
@@ -22,4 +22,13 @@ def shell
MyCounter.new([1,2]).shell.must be_kind_of(Thor::Base.shell)
end
end
+
+ describe "with_padding" do
+ it "uses padding for inside block outputs" do
+ base = MyCounter.new([1,2])
+ base.with_padding do
+ capture(:stdout){ base.say_status :padding, "cool" }.strip.must == "padding cool"
+ end
+ end
+ end
end

0 comments on commit e93882a

Please sign in to comment.