Class: Flexi::Json::Searcher

Inherits:
Object
  • Object
show all
Defined in:
lib/flexi/json/searcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data) ⇒ Searcher

Returns a new instance of Searcher.



8
9
10
11
# File 'lib/flexi/json/searcher.rb', line 8

def initialize(data)
  @data = data
  @result = []
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



6
7
8
# File 'lib/flexi/json/searcher.rb', line 6

def data
  @data
end

#resultObject (readonly)

Returns the value of attribute result.



6
7
8
# File 'lib/flexi/json/searcher.rb', line 6

def result
  @result
end

Instance Method Details

#display_results(results = @result, output = $stdout) ⇒ Object

Displays results to the console



35
36
37
38
39
40
41
42
43
44
# File 'lib/flexi/json/searcher.rb', line 35

def display_results(results = @result, output = $stdout)
  if results.empty?
    output.puts "No data found."
  else
    results.each do |result|
      output.puts result.attributes.map { |k, v| "#{k}: #{v}" }.join(", ")
    end
    output.puts "Found #{results.size} result(s)!"
  end
end

#find_duplicates(keys) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/flexi/json/searcher.rb', line 17

def find_duplicates(keys)
  duplicates = {}
  fields = keys.gsub(/\s+/, "").strip.split(",")
  filtered_fields = fields.select { |field| @data.first&.searchable_fields&.include?(field) }

  return [] if filtered_fields.empty?

  grouped_data = @data.group_by do |d|
    filtered_fields.map { |f| d.attributes[f.to_sym].to_s.downcase }
  end
  grouped_data.each do |key, value|
    duplicates[key] = value if value.size > 1
  end

  @result = duplicates.values.flatten
end

#search(query, fields = nil, options: nil) ⇒ Object



13
14
15
# File 'lib/flexi/json/searcher.rb', line 13

def search(query, fields = nil, options: nil)
  @result = @data.select { |data| data.matches?(query, fields, options: options) }
end