Class: PecoSelector::Selector

Inherits:
Object
  • Object
show all
Defined in:
lib/peco_selector.rb

Constant Summary collapse

PECO_BIN =
"peco"
Error =
Class.new(StandardError)

Instance Method Summary collapse

Instance Method Details

#select_from(candidates, options = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/peco_selector.rb', line 14

def select_from(candidates, options = {})
  prompt = options[: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|
      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 |_, value|
    value
  end.select do |value|
    object_ids.include?(value.object_id)
  end
end