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

Prioritise commands by match_score [Fixes #471]

This commit is contained in:
Conrad Irwin 2012-02-11 15:15:22 -08:00
parent a249a54042
commit 4e8a436460
3 changed files with 37 additions and 1 deletions

View file

@ -83,6 +83,30 @@ class Pry
command_regex =~ val
end
# How well does this command match the given line?
#
# Higher scores are better because they imply that this command matches
# the line more closely.
#
# The score is calculated by taking the number of characters at the start
# of the string that are used only to identify the command, not as part of
# the arguments.
#
# @example
# /\.(.*)/.match_score(".foo") #=> 1
# /\.*(.*)/.match_score("...foo") #=> 3
# 'hi'.match_score("hi there") #=> 2
#
# @param String a line input at the REPL
# @return Fixnum
def match_score(val)
if command_regex =~ val
Regexp.last_match.size > 1 ? Regexp.last_match.begin(1) : Regexp.last_match.end(0)
else
-1
end
end
# Store hooks to be run before or after the command body.
# @see {Pry::CommandSet#before_command}
# @see {Pry::CommandSet#after_command}

View file

@ -281,7 +281,7 @@ class Pry
# @param [String] the line that may be a command invocation
# @return [Pry::Command, nil]
def find_command(val)
commands.values.detect{ |c| c.matches?(val) }
commands.values.select{ |c| c.matches?(val) }.sort_by{ |c| c.match_score(val) }.last
end
# Is the given line a command invocation?

View file

@ -471,6 +471,18 @@ describe Pry::CommandSet do
@set.find_command('colon').should == cmd
Pry.config.command_prefix = ''
end
it "should find the command that has the longest match" do
cmd = @set.command(/\.(.*)/){ }
cmd2 = @set.command(/\.\|\|(.*)/){ }
@set.find_command('.||').should == cmd2
end
it "should find the command that has the longest name" do
cmd = @set.command(/\.(.*)/){ }
cmd2 = @set.command('.||'){ }
@set.find_command('.||').should == cmd2
end
end
describe '.valid_command?' do