Method: Wik#find

Defined in:
lib/wik.rb

#find(phrase, limit = 15, snippet = false, display = true) ⇒ Object

Do a search by phrase, returns a hash with full search data, but first prints the parsed search data



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
# File 'lib/wik.rb', line 23

def find(phrase, limit=15, snippet=false, display=true)
  search = phrase.split.join("_")
  if snippet
    endpoint = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=#{search}&srlimit=#{limit}"
  else
    endpoint = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=#{search}&srlimit=#{limit}&srprop"
  end
  hash = get(endpoint)
  info = hash["query"]["searchinfo"]
  results = hash["query"]["search"]
  if display
    puts "Total hits : #{ info["totalhits"] }"
    if info["suggestion"]
      puts "Suggestion : #{ info["suggestion"] }"
    end
    puts "Displaying #{results.length} results:"
    results.each do |result|
      # https://stackoverflow.com/a/1732454
      if snippet
        snip = result["snippet"].gsub( /<.*?>/, "" ).gsub( /&\w+;/, "" ).split.join(" ")
        puts "\n'#{result["title"]}' : #{snip}..."
      else
        puts "\n'#{result["title"]}'"
      end
    end
  end
  return hash
end