Module: PecoSelector
- Defined in:
- lib/peco_selector.rb,
lib/peco_selector/version.rb
Constant Summary collapse
- PECO_BIN =
"peco"- Error =
Class.new(StandardError)
Class.new(StandardError)
- VERSION =
"0.0.5"
Class Method Summary collapse
- .ensure_peco_available ⇒ Object
- .peco_available? ⇒ Boolean
- .select_from(candidates, options = {}) ⇒ Object
Class Method Details
.ensure_peco_available ⇒ Object
14 15 16 17 18 |
# File 'lib/peco_selector.rb', line 14 def self.ensure_peco_available unless peco_available? raise PecoUnavailableError, "Peco command is unavailable. (see https://github.com/peco/peco#installation)" end end |
.peco_available? ⇒ Boolean
10 11 12 |
# File 'lib/peco_selector.rb', line 10 def self.peco_available? system('which', PECO_BIN, out: File::NULL) end |
.select_from(candidates, options = {}) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/peco_selector.rb', line 20 def self.select_from(candidates, = {}) ensure_peco_available prompt = [:prompt] || "QUERY>" stdout_str = nil stderr_str = nil Open3.popen3("#{PECO_BIN} --null --prompt #{Shellwords.escape(prompt)}") do |stdin, stdout, stderr, wait_thr| candidates.each do |display, value| value ||= display stdin.puts "#{display}\x00#{value.object_id}" end stdin.close stdout_str = stdout.read stderr_str = stderr.read unless wait_thr.value.exitstatus == 0 $stdout.print stdout_str $stderr.print stderr_str abort end end object_ids = stdout_str.strip.split("\n").map(&:to_i) candidates.map do |display, value| value || display end.select do |value| object_ids.include?(value.object_id) end end |