Is it possible to stringify parameters in ruby/irb?
I'm new to ruby ... wondering if the following is possible:
I currently run a test app within irb (irb -r test.rb) and manually execute various command implemented in test.rb. One of these functions is currently implemented as follows:
def cli(cmd)
ret=$client开发者_如何学运维.Cli(cmd)
print ret, "\n"
end
Where $client.Cli()
takes a string. I currently type the following in the IRB prompt
> cli "some command with parameters"
This is sent over socket and results are returned
I would like to be able to do this WITHOUT the quotes. This would be just for this command Is there a way to do this generally in ruby? if not how would you extend irb to do this?
For those who know 'C' this would be like the following:
#define CLI(CMD) cli(#CMD)
CLI(Quadafi and Sheen walk into a bar...)
where the pre-processed output is:
cli("Quadafi and Sheen walk into a bar...")
Thanks
You could actually monkey patch the gets
method of the IRB::StdioInputMethod
and IRB::ReadlineInputMethod
classes, and perform a rewrite if the cli
method is called, by adding the following to your test.rb
file:
module IRB
def self.add_quotes(str)
str.gsub(/^cli (..+?)(\\+)?$/, 'cli "\1\2\2"') unless str.nil?
end
class StdioInputMethod
alias :old_gets :gets
def gets
IRB::add_quotes(old_gets)
end
end
class ReadlineInputMethod
alias :old_gets :gets
def gets
IRB::add_quotes(old_gets)
end
end
end
This way, any input line matching cli ...
will be replaced with cli "..."
before it's evaluated.
I don't think it's possible, because the command that you type to irb has to parse as ruby, and all those bare words will report errors like this:
NameError: undefined local variable or method `hello' for main:Object
(My first attempt, I just called it via cli hello
.)
But if you didn't mind a more radical change, you could do something like this:
$ cat /tmp/test_cases
hello world
one
two
three
riding the corpse sled
$ ruby -e 'def f(arg) puts arg end' -ne 'f($_)' < /tmp/test_cases
hello world
one
two
three
riding the corpse sled
I just defined a simple function f()
here that would show how it works; you could replace f($_)
with $Client.cli($_)
, and set up the $Client
global variable in the first -e
argument. And you can leave off the < /tmp/test_cases
if you want to type them in interactively:
$ ruby -e 'def f(arg) puts arg end' -ne 'f($_)'
hello
hello
world
world
Of course, if you want it to be any more advanced than this, I'd just write a script to do it all, rather than build something hideous from -pe
or -ne
commands.
精彩评论