[ruby/irb] Simplify command method definition

(https://github.com/ruby/irb/pull/559)

* Remove unnecessary command argument generation code

Now that all the supported Ruby versions handle splat args and splat kwargs,
we don't need that args generation code anymore.

* Remove unused command definition code

If we look at `@EXTEND_COMMANDS`, all commands are defined in a file, which
means the `if load_file` branch is always executed. Therefore we can drop
the else branch of that condition.

* Avoid defining unnecessary command methods

There's no need to define another command method just to call `Command.execute`.
This commit is contained in:
Stan Lo 2023-04-08 11:11:46 +01:00 committed by git
parent 08324ab9eb
commit e7f77e1e89

View File

@ -246,7 +246,7 @@ module IRB # :nodoc:
#
# The optional +load_file+ parameter will be required within the method
# definition.
def self.def_extend_command(cmd_name, cmd_class, load_file = nil, *aliases)
def self.def_extend_command(cmd_name, cmd_class, load_file, *aliases)
case cmd_class
when Symbol
cmd_class = cmd_class.id2name
@ -255,33 +255,12 @@ module IRB # :nodoc:
cmd_class = cmd_class.name
end
if load_file
line = __LINE__; eval %[
def #{cmd_name}(*opts, **kwargs, &b)
Kernel.require_relative "#{load_file}"
arity = ::IRB::ExtendCommand::#{cmd_class}.instance_method(:execute).arity
args = (1..(arity < 0 ? ~arity : arity)).map {|i| "arg" + i.to_s }
args << "*opts, **kwargs" if arity < 0
args << "&block"
args = args.join(", ")
line = __LINE__; eval %[
unless singleton_class.class_variable_defined?(:@@#{cmd_name}_)
singleton_class.class_variable_set(:@@#{cmd_name}_, true)
def self.#{cmd_name}_(\#{args})
::IRB::ExtendCommand::#{cmd_class}.execute(irb_context, \#{args})
end
end
], nil, __FILE__, line
__send__ :#{cmd_name}_, *opts, **kwargs, &b
end
], nil, __FILE__, line
else
line = __LINE__; eval %[
def #{cmd_name}(*opts, &b)
::IRB::ExtendCommand::#{cmd_class}.execute(irb_context, *opts, &b)
end
], nil, __FILE__, line
end
line = __LINE__; eval %[
def #{cmd_name}(*opts, **kwargs, &b)
Kernel.require_relative "#{load_file}"
::IRB::ExtendCommand::#{cmd_class}.execute(irb_context, *opts, **kwargs, &b)
end
], nil, __FILE__, line
for ali, flag in aliases
@ALIASES.push [ali, cmd_name, flag]