Class: AIA::Fzf

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

Constant Summary collapse

DEFAULT_PARAMETERS =
%w[
  --tabstop=2
  --header-first
  --prompt='Search term: '
  --delimiter :
  --preview-window=down:50%:wrap
]

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(list:, directory:, query: '', subject: 'Prompt IDs', prompt: 'Select one:', extension: '.md') ⇒ Fzf

Returns a new instance of Fzf.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/aia/fzf.rb', line 19

def initialize(
    list:,          # Array of Strings (basenames of files w/o extension)
    directory:,     # Parent directory of the list items
    query:      '', # String, the thing be searched for
    subject:    'Prompt IDs', # or 'Role Names'
    prompt:     'Select one:',
    extension:  '.md'
  )

  @list       = list
  @directory  = directory
  @query      = query
  @subject    = subject
  @prompt     = prompt
  @extension  = extension

  build_command
end

Instance Attribute Details

#commandObject (readonly)

Returns the value of attribute command.



17
18
19
# File 'lib/aia/fzf.rb', line 17

def command
  @command
end

#directoryObject (readonly)

Returns the value of attribute directory.



17
18
19
# File 'lib/aia/fzf.rb', line 17

def directory
  @directory
end

#extensionObject (readonly)

Returns the value of attribute extension.



17
18
19
# File 'lib/aia/fzf.rb', line 17

def extension
  @extension
end

#listObject (readonly)

Returns the value of attribute list.



17
18
19
# File 'lib/aia/fzf.rb', line 17

def list
  @list
end

#promptObject (readonly)

Returns the value of attribute prompt.



17
18
19
# File 'lib/aia/fzf.rb', line 17

def prompt
  @prompt
end

#queryObject (readonly)

Returns the value of attribute query.



17
18
19
# File 'lib/aia/fzf.rb', line 17

def query
  @query
end

#subjectObject (readonly)

Returns the value of attribute subject.



17
18
19
# File 'lib/aia/fzf.rb', line 17

def subject
  @subject
end

Instance Method Details

#build_commandObject



39
40
41
42
43
44
45
46
47
48
# File 'lib/aia/fzf.rb', line 39

def build_command
  fzf_options = DEFAULT_PARAMETERS.dup
  escaped_dir = Shellwords.escape(directory)
  escaped_ext = Shellwords.escape(extension)
  fzf_options << "--header=#{Shellwords.escape("#{subject} which contain: #{query}\nPress ESC to cancel.")}"
  fzf_options << "--preview=#{Shellwords.escape("cat #{escaped_dir}/{1}#{escaped_ext}")}"
  fzf_options << "--prompt=#{Shellwords.escape(prompt)}"

  @fzf_args = fzf_options
end

#runObject



51
52
53
54
55
56
57
58
# File 'lib/aia/fzf.rb', line 51

def run
  input = list.join("\n")
  selected, status = Open3.capture2('fzf', *@fzf_args, stdin_data: input)

  selected.strip.empty? ? nil : selected.strip
ensure
  unlink_tempfile
end