Skip to content

Instantly share code, notes, and snippets.

@leonid-shevtsov
Created July 1, 2013 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leonid-shevtsov/5903356 to your computer and use it in GitHub Desktop.
Save leonid-shevtsov/5903356 to your computer and use it in GitHub Desktop.
Fixed auto-link web search for Markdown Service Tools
require 'net/http'
require 'net/https'
require 'openssl'
require 'uri'
def fetch_with_redirect(uri_str, limit = 10)
return nil if limit==0
uri = URI.parse(uri_str)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new uri.request_uri
response = http.request request
if response.is_a? Net::HTTPRedirection
location = response['location']
fetch_with_redirect(location, limit - 1)
else
response.body
end
end
ARGF.each do |input|
res = fetch_with_redirect("https://duckduckgo.com/?q=%5C#{URI.escape(input)}%2F")
if res
match = res.strip.match(/URL='(.*?)'/)
unless match.nil?
print %Q{[#{input.strip}](#{match[1].strip})}
else
print input
end
else
print input
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment