Class: Gm::Notepad::InputHandlers::QueryTableHandler

Inherits:
DefaultHandler show all
Extended by:
Forwardable
Defined in:
lib/gm/notepad/input_handlers/query_table_handler.rb

Constant Summary collapse

QUERY_TABLE_NAMES_PREFIX =
'+'.freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from DefaultHandler

build_if_handled, #initialize, #lines

Constructor Details

This class inherits a constructor from Gm::Notepad::InputHandlers::DefaultHandler

Class Method Details

.handles?(input:) ⇒ Boolean

Returns:

  • (Boolean)


10
11
12
13
14
15
16
17
18
# File 'lib/gm/notepad/input_handlers/query_table_handler.rb', line 10

def self.handles?(input:)
  # Does not have the table prefix
  return false unless input.match(/^\+/)
  # It is only the table prefix
  return false if input.match(/^\+$/)
  # It is querying all tables by way of grep
  return false if input.match(/^\+\//)
  true
end

Instance Method Details

#after_initialize!Object



20
21
22
23
24
# File 'lib/gm/notepad/input_handlers/query_table_handler.rb', line 20

def after_initialize!
  line = input[1..-1].to_s
  @table_lookup_parameters = Parameters::TableLookup.new(text: line)
  evaluate_lines!
end

#evaluate_lines!Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/gm/notepad/input_handlers/query_table_handler.rb', line 29

def evaluate_lines!
  begin
    table = table_registry.fetch_table(name: table_name)
  rescue MissingTableError
    message = "Unknown table #{table_name.inspect}. Did you mean: "
    message += table_registry.table_names.grep(/\A#{table_name}/).map(&:inspect).join(", ")
    input.for_rendering(text: message, to_output: false, to_interactive: true, expand_line: false)
    return
  end
  if index
    begin
      text = table.lookup(index: index)
      input.for_rendering(text: text, to_output: false, to_interactive: true, expand_line: false)
    rescue MissingTableEntryError
      input.for_rendering(text: %(Entry with index "#{index}" not found in "#{table_name}" table), to_interactive: true, to_output: false)
    end
  elsif grep
    regexp = %r{#{grep}}i
    table.grep(regexp).each do |text|
      input.for_rendering(text: text, to_output: false, to_interactive: true, expand_line: false)
    end
  else
    table.all.each do |text|
      input.for_rendering(text: text, to_output: false, to_interactive: true, expand_line: false)
    end
  end
end