Pre-populated Ruby tooltip

I use Ruby to write a small Pubmed search command line utility. Right now, I invite the user to fulfill the query and display the results, and the user has the ability to add to the query or enter a completely new query. I would like to add the ability to edit the current request; i.e. the request must be pre-populated with an editable version of the previous request, for example:

Enter query: <PREVIOUS QUERY HERE> 

It’s easy enough to print the previous request next to the invitation, but how to make this conclusion editable, as if the user typed it?

@casper: Thanks for the answer Casper. I tried the code you provided below and it really works on its own. Oddly enough, it does not work when I try to use it in a gem. My gem is called db_hippo. I added rb-readline as a dependency in my gemspec and I put the extension in RbReadline in lib / db_hippo / rb-readline.rb

 module DbHippo module RbReadline <CASPER EXTENSION HERE> end end 

I want to use the functionality in another sub-module of DbHippo, DbHippo :: Source. In DbHippo :: Source, I added above:

 require 'rb-readline' require 'db_hippo/rb-readline' 

Then in one of the methods of DbHippo :: Source I:

 RbReadline.prefill_prompt(query) query = Readline.readline("Query: ", true) 

The request variable is definitely not empty, but for some reason the prompt is not populated in this context. I also notice that if I put the extension in the same file (lib / db_hippo / rb-readline) without making it a submodule of DbHippo, I get an error: uninitialized constant DbHippo :: Source :: Readline (NameError) in the line:

 query = Readline.readline("Query: ", true) 

All this seems to be related to the correct name of the modules, it requires statements and gems. This is the first stone I tried to build. Any idea what is going wrong here?

+4
source share
2 answers

You can do this with RbReadline :

 require 'rubygems' require 'rb-readline' module RbReadline def self.prefill_prompt(str) @rl_prefill = str @rl_startup_hook = :rl_prefill_hook end def self.rl_prefill_hook rl_insert_text @rl_prefill if @rl_prefill @rl_startup_hook = nil end end RbReadline.prefill_prompt("Previous query") str = Readline.readline("Enter query: ", true) puts "You entered: #{str}" 
+2
source

Perhaps googlers will find this useful.

With a regular Readline on Ruby 2.1 you can use:

 def ask(prompt, default=nil) if default Readline.pre_input_hook = -> { Readline.insert_text(default) Readline.redisplay } end data = Readline.readline("#{prompt}: ") return data.chomp end ask("MOAR...?", "COMPUTARS!") # displays: MOAR...? COMPUTARS! 

At the command prompt, the text COMPUTARS! will be editable

+3
source

All Articles