Class: Unitsdb::Commands::Search

Inherits:
Base
  • Object
show all
Defined in:
lib/unitsdb/commands/search.rb

Instance Method Summary collapse

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from Unitsdb::Commands::Base

Instance Method Details

#run(query) ⇒ Object



10
11
12
13
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/unitsdb/commands/search.rb', line 10

def run(query)
  # Database path is guaranteed by Thor's global option

  type = @options[:type]
  id = @options[:id]
  id_type = @options[:id_type]
  format = @options[:format] || "text"

  begin
    database = load_database(@options[:database])

    # Search by ID (early return)
    if id
      entity = database.get_by_id(id: id, type: id_type)

      unless entity
        puts "No entity found with ID: '#{id}'"
        return
      end

      # Use the same output logic as the Get command
      if %w[json yaml].include?(format.downcase)
        begin
          puts entity.send("to_#{format.downcase}")
          return
        rescue NoMethodError
          puts "Error: Unable to convert entity to #{format} format"
          exit(1)
        end
      end

      print_entity_details(entity)
      return
    end

    # Regular text search
    results = database.search(text: query, type: type)

    # Early return for empty results
    if results.empty?
      puts "No results found for '#{query}'"
      return
    end

    # Format-specific output
    if %w[json yaml].include?(format.downcase)
      temp_db = create_temporary_database(results)
      puts temp_db.send("to_#{format.downcase}")
      return
    end

    # Default text output
    puts "Found #{results.size} result(s) for '#{query}':"
    results.each do |entity|
      print_entity_with_ids(entity)
    end
  rescue Unitsdb::Errors::DatabaseError => e
    puts "Error: #{e.message}"
    exit(1)
  rescue StandardError => e
    puts "Error searching database: #{e.message}"
    exit(1)
  end
end