Last active
August 29, 2015 13:57
-
-
Save arashm/9599870 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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