Class: FetchUtil::Searcher

Inherits:
Object
  • Object
show all
Defined in:
lib/fetch_util/searcher.rb,
lib/fetch_util/searcher/result_filtering.rb

Constant Summary collapse

MAX_SNIPPET_LENGTH =
180
SOURCES =
{
  "duckduckgo" => "https://duckduckgo.com/?q=%<query>s&ia=web&kl=us-en",
  "google" => "https://www.google.com/search?hl=en&q=%<query>s",
  "bing" => "https://www.bing.com/search?setlang=en-US&q=%<query>s",
  "ecosia" => "https://www.ecosia.org/search?q=%<query>s",
  "brave" => "https://search.brave.com/search?q=%<query>s"
}.freeze
DEFAULT_SOURCES =
%w[duckduckgo google].freeze

Instance Method Summary collapse

Constructor Details

#initialize(fetcher: nil, request_log: RequestLog.new, sources: nil, limit: 10, concurrency: 2, verbose: false, **fetch_options) ⇒ Searcher

Returns a new instance of Searcher.



24
25
26
27
28
29
30
# File 'lib/fetch_util/searcher.rb', line 24

def initialize(fetcher: nil, request_log: RequestLog.new, sources: nil, limit: 10, concurrency: 2, verbose: false, **fetch_options)
  @request_log = request_log
  @sources = Array(sources || DEFAULT_SOURCES).map(&:to_s)
  @limit = limit.to_i
  @verbose = verbose
  @fetcher = fetcher || ParallelFetcher.new(concurrency: concurrency, request_log: request_log, **fetch_options)
end

Instance Method Details

#search(query) ⇒ Object

Raises:

  • (ArgumentError)


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/fetch_util/searcher.rb', line 32

def search(query)
  encoded_query = query.to_s.strip
  raise ArgumentError, "query must not be empty" if encoded_query.empty?

  urls = search_urls(encoded_query)
  @request_log.append(search_request_uri(encoded_query))
  fetched = begin
    @fetcher.fetch(urls.values)
  rescue ParallelFetcher::ParallelFetchError => e
    raise unless e.results&.compact&.any?

    e.results
  end

  {
    query: encoded_query,
    results: formatted_results(aggregate(urls.keys, fetched).first(limit))
  }
end