1
0
Fork 0
mirror of https://github.com/pry/pry.git synced 2022-11-09 12:35:05 -05:00

Added Pry::CommandSet#helpers

This commit is contained in:
Mon ouïe 2011-04-30 12:28:58 +02:00
parent e3becbfbf6
commit 943c5cd152
2 changed files with 68 additions and 3 deletions

View file

@ -23,14 +23,16 @@ class Pry
attr_reader :commands
attr_reader :name
attr_reader :helper_module
# @param [Symbol] name Name of the command set
# @param [Array<CommandSet>] imported_sets Sets which will be imported
# automatically
# @yield Optional block run to define commands
def initialize(name, *imported_sets, &block)
@name = name
@commands = {}
@name = name
@commands = {}
@helper_module = Module.new
define_default_commands
import(*imported_sets)
@ -94,7 +96,10 @@ class Pry
# @param [Array<CommandSet>] sets Command sets, all of the commands of which
# will be imported.
def import(*sets)
sets.each { |set| commands.merge! set.commands }
sets.each do |set|
commands.merge! set.commands
helper_module.send :include, set.helper_module
end
end
# Imports some commands from a set
@ -121,6 +126,8 @@ class Pry
# @param [Array<Object>] args Arguments passed to the command
# @raise [NoCommandError] If the command is not defined in this set
def run_command(context, name, *args)
context.extend helper_module
if command = commands[name]
command.call(context, *args)
else
@ -140,6 +147,22 @@ class Pry
commands[name].description = description
end
# Defines helpers methods for this command sets.
# Those helpers are only defined in this command set.
#
# @yield A block defining helper methods
# @example
# helpers do
# def hello
# puts "Hello!"
# end
#
# include OtherModule
# end
def helpers(&block)
helper_module.class_eval(&block)
end
private
def define_default_commands
command "help", "This menu." do |cmd|

View file

@ -925,4 +925,46 @@ describe Pry::CommandSet do
@set.command('foo', '', :keep_retval => true) { 3 }
@set.run_command(nil, 'foo').should == 3
end
it 'should be able to have its own helpers' do
@set.command('foo') do
should.respond_to :my_helper
end
@set.helpers do
def my_helper; end
end
@set.run_command(Pry::CommandContext.new, 'foo')
Pry::CommandContext.new.should.not.respond_to :my_helper
end
it 'should not recreate a new heler module when helpers is called' do
@set.command('foo') do
should.respond_to :my_helper
should.respond_to :my_other_helper
end
@set.helpers do
def my_helper; end
end
@set.helpers do
def my_other_helper; end
end
@set.run_command(Pry::CommandContext.new, 'foo')
end
it 'should import helpers from imported sets' do
imported_set = Pry::CommandSet.new :test do
helpers do
def imported_helper_method; end
end
end
@set.import imported_set
@set.command('foo') { should.respond_to :imported_helper_method }
@set.run_command(Pry::CommandContext.new, 'foo')
end
end