Top Level Namespace

Constant Summary collapse

GOOGLE_SEARCH_URL =
"http://www.google.com/search?q=site:stackoverflow.com+"
USER_AGENT =
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17"

Instance Method Summary collapse

Instance Method Details



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

def get_google_links(args)
  page = get_url(URI.escape(GOOGLE_SEARCH_URL + args.join("+")))
  html = Nokogiri.HTML(page)
  posts = []
  html.css('a.l').each{|l| posts << l[:href] if is_question?(l[:href]) }
  posts
end


32
33
34
35
36
37
38
39
# File 'lib/howdoi.rb', line 32

def get_link_at_pos(links, pos)
  link = nil
  pos.times do |i|
    break if i > links.size
    link = links[i]
  end
  link
end

#get_url(url) ⇒ Object



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

def get_url(url) 
  uri = URI.parse url
  http = Net::HTTP.new(uri.host, uri.port)
  http.get(uri.request_uri, 'User-Agent' => USER_AGENT).body
end

#how_do_i(args, opts = {}) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/howdoi.rb', line 41

def how_do_i(args, opts = {})
  links = get_google_links(args)
  link = get_link_at_pos(links, opts[:pos])
  if link
    puts "\e[32m" + link + "\e[m"
    puts 
    page = get_url link
    html = Nokogiri.HTML page
    ans = html.at_css(".answer")
    if ans
      instruction = ans.css("pre").children.
        collect(&:content).
        join(" " * 5 + '-' * 50 + "\n") || 
        ans.at_css("code").content
      unless opts[:all] or instruction.empty?
        puts instruction
      else
        puts ans.at('.post-text').content
      end
    end
    exit
  end
  puts "Sorry, couldn't find any help with that topic"
end

#is_question?(stackoverflow_url) ⇒ Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/howdoi.rb', line 20

def is_question?(stackoverflow_url)
  stackoverflow_url =~ %r(/questions/\d+/)
end