I have a registry (array) of CLI classes. Each class has a class
method cli() that returns an array of strings or regular expressions
to match against ARGV to see if it is the chosen cli. Eg.
class FooList << CLIBase
def self.cli ; ['foo', 'list'] ; end
...
end
So if someone puts on the command line:
$ foo list
Then the above class would match for it. I wrote the algorithm to
handle this, but I think it's Ugh-ly. Wondering if the smart folk here
might play a game of golf on it.
def command(argv)
lookup = registry.map{ |cc| [cc, cc.cli] }.sort{ |a,b| b[1].size
<=> a[1].size }
x = lookup.find do |cc, cli|
t = true
cli.each_with_index do |r, i|
t = t && (r === argv[i])
end
t
end
cmdc = x[0]
argv = argv[x[1].size..-1]
return cmdc, argv
end
def command(argv)
lookup = registry.map{ |cc| [cc, cc.cli] }.sort{ |a,b| b[1].size
<=> a[1].size }
x = lookup.find do |cc, cli|
t = true
cli.each_with_index do |r, i|
t = t && (r === argv[i])
end
t
end
cmdc = x[0]
argv = argv[x[1].size..-1]
return cmdc, argv
end
Untested:
def command(argv)
lookup = registry.sort_by {|cc| cc.cli.size}
cmdc = lookup.find do |cc|
cc.cli.zip(argv).all? do |r,arg|
r === arg
end
end
return cmdc, argv[cmdc.cli.size..-1]
end
The following (assuming it works!) would be more compact still:
class Symbol
alias old_to_proc to_proc
def to_proc
case self
when :=== # etc.
proc {|x,y| x === y}
else
old_to_proc
end
end
end
def command(argv)
lookup = registry.sort_by {|cc| cc.cli.size}
cmdc = lookup.find do |cc|
cc.cli.zip(argv).all?(&:===)
end
return cmdc, argv[cmdc.cli.size..-1]
end
Thanks Joel and Martin. Amazingly concise answers -- it's amazes me
sometimes how small a piece of code can get in Ruby
I haven't gotten back to the particular code I need this for yet which
is why I haven't responded until now, but should be back to it soon
and I'll let you know how it worked out.