Class: Google_search_cmdline

Inherits:
Object
  • Object
show all
Defined in:
lib/google_search_cmdline.rb

Overview

Main class that holds functionality for actually executing the Google-search.

Examples

gsc = Google_search_cmdline.new
gsc.search("something").each do |result|
  #do something with the result
end

Defined Under Namespace

Classes: Interface, Result

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.const_missing(name) ⇒ Object

Autoloader for subclasses.


14
15
16
17
18
# File 'lib/google_search_cmdline.rb', line 14

def self.const_missing(name)
  require "#{File.dirname(__FILE__)}/google_search_cmdline_#{name.to_s.downcase}.rb"
  raise "Still not loaded: '#{name}'." if !Google_search_cmdline.const_defined?(name)
  return Google_search_cmdline.const_get(name)
end

Instance Method Details

#search(text) ⇒ Object

This is used to execute a Google-search based on the given text.

Examples

enum = gsc.search("something")
enum.each do |result|
  puts "Title: #{result.title}"
  puts "URL: #{result.url}"
end

27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/google_search_cmdline.rb', line 27

def search(text)
  return Enumerator.new do |y|
    Http2.new(:host => "www.google.com", :port => 80) do |http|
      escaped_str = CGI.escape(text)
      res = http.get("search?q=#{escaped_str}&oq=#{escaped_str}&sugexp=mod=0&ie=UTF-8")
      
      doc = Nokogiri.HTML(res.body)
      doc.css("li.g > h3.r a").each do |a|
        title = a.content
        google_url = a.attribute("href").content
        
        if !match_url = google_url.match(/\/url\?q=(.+?)&sa=U&ei=/)
          raise "Could not match that Google URL: '#{google_url}'."
        end
        
        url = match_url[1]
        y << Google_search_cmdline::Result.new(:title => title, :url => url)
      end
    end
  end
end