Created
October 31, 2020 01:28
-
-
Save mnbi/480ceb656db005d478566f137a8e470d to your computer and use it in GitHub Desktop.
Invoke a picker in program code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# How to invoke a picker in your code to select items interactively. | |
PICKER = 'fzf' | |
PICKER_OPTS = '-m' # allow multiple selection | |
def picker(prog, entries) | |
in_ary = entries.map(&:to_s) | |
IO.popen(prog, "r+") { |pipe| | |
in_ary.each {|e| pipe.puts(e)} | |
pipe.close_write | |
pipe.readlines.map {|line| entries[in_ary.index(line.chomp)]} | |
} | |
end | |
# integers | |
data = [1, 1, 2, 3, 5, 8, 13, 21] | |
selected = picker([PICKER, PICKER_OPTS], data) | |
pp selected | |
# strings | |
data = Dir.glob(File.expand_path("*", "~")) | |
selected = picker([PICKER, PICKER_OPTS], data) | |
pp selected | |
# complex structures | |
data = [["iMac", 2020], ["Mac mini", 2009], ["iPhone SE", 2020], ["iPad", 2010]] | |
selected = selected = picker([PICKER, PICKER_OPTS], data) | |
pp selected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment