Skip to content

Instantly share code, notes, and snippets.

@arashm
Last active August 29, 2015 13:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arashm/9599870 to your computer and use it in GitHub Desktop.
Save arashm/9599870 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'nokogiri' # gem install nokogiri --no-document
require 'net/http'
require 'json'
require 'cgi'
# Suppose you want to know how to format a date in bash. Why open your browser and read through
# blogs (risking major distraction) when you can simply stay in the console and ask howdoi:
# $ ruby howdoi.rb format date bash
# > DATE=`date +%Y-%m-%d`
# This is a simple clone of https://github.com/gleitz/howdoi/
class HowDoI
# more information in https://api.stackexchange.com/docs/answers-on-questions
STACK_API_URL = "https://api.stackexchange.com/2.2/questions/%{id}/answers?order=desc&sort=votes&site=stackoverflow&filter=!4*8OiBHomm4Ah26RX"
GOOGLE_SEARCH_URL = "https://www.google.com/search?q=site:stackoverflow.com%20"
def initialize(query)
@query = CGI.escape(query)
get_code_block
end
def to_s
@code_block
end
private
def get_code_block
doc = Nokogiri::HTML( search_stack )
@code_block = doc.css('code').collect { |node| node.text }[0].chomp
end
def search_stack
body = Net::HTTP.get URI(STACK_API_URL % {id: search_google})
JSON(body)['items'].first['body']
end
def search_google
doc = Nokogiri::HTML Net::HTTP.get(URI(GOOGLE_SEARCH_URL + @query))
links = []
doc.css('li.g h3.r a').each do |result|
links << URI.extract(result['href'])
end
get_questions_id(links.flatten.first)
end
def get_questions_id(url)
matched = url.match(/\/(\d+)\//)
matched[1]
end
end
# Gets the query from commandline
puts HowDoI.new ARGV.join(' ')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment