diff --git a/lib/pry/command_set.rb b/lib/pry/command_set.rb index b2ca1e56..b4cef873 100644 --- a/lib/pry/command_set.rb +++ b/lib/pry/command_set.rb @@ -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] 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] 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] 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| diff --git a/test/test.rb b/test/test.rb index 47ea706c..3bcc9a29 100644 --- a/test/test.rb +++ b/test/test.rb @@ -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