Create a gist now

Instantly share code, notes, and snippets.

gem_visit command line utility
#!/usr/bin/env ruby
# Call the file just `gem-visit`, not `gem-visit.rb`, and put it in your path
# (maybe you want ~/bin in your $PATH), to be able to do:
#
# . gem-visit name_of_gem
#
# And have a browser window opened pointing to the (preferable, if it can) github
# homepage of the gem, or other gem project page (last resort).
require 'net/http'
require 'json'
API_HOST = "rubygems.org"
PREFERRED_URI_RE = %r{\Ahttps?\://github.com}
OPEN_CMD = 'open %s'
def usage(err_msg = nil)
usage = "USAGE: gem_visit gem_name"
if err_msg
usage = "Error: #{err_msg}\n#{usage}"
end
usage
end
def present?(str)
str && ! str.empty?
end
gem_name = ARGV[0]
unless gem_name
$stderr.puts usage("Need a gem name")
exit 1
end
http = Net::HTTP.new(API_HOST, 443).tap { |h| h.use_ssl = true }
response = http.get("/api/v1/gems/#{gem_name}.json")
if response.code == "404"
$stderr.puts "rubygems can't find gem named `#{gem_name}`"
exit 1
end
unless response.code == "200"
$stderr.puts "Error from rubygems: #{response}"
exit 1
end
data = JSON.parse(response.body)
go_to_url = if present?(data["homepage_uri"]) && data["homepage_uri"] =~ PREFERRED_URI_RE
data["homepage_uri"]
elsif present?(data["source_code_uri"]) && data["source_code_uri"] =~ PREFERRED_URI_RE
data["source_code_uri"]
elsif present?(data["homepage_uri"])
data["homepage_uri"]
elsif present?(data["source_code_uri"])
data["source_code_uri"]
else
data["project_uri"]
end
`#{OPEN_CMD % go_to_url}`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment