Created
August 5, 2021 10:45
-
-
Save arashm/be888d91e1b0560e13a3fa98edce8570 to your computer and use it in GitHub Desktop.
Fetch gems info from rubygems.org and pretty print it to terminal
This file contains hidden or 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 'bundler/inline' | |
gemfile do | |
source 'https://rubygems.org' | |
gem 'rest-client' | |
gem 'colorize' | |
end | |
require 'rest-client' | |
require 'colorize' | |
require 'date' | |
require 'json' | |
class GemInfo | |
def initialize(args) | |
@endpoint = 'https://rubygems.org/api/v1/' | |
@args = args | |
end | |
# Iterate over provided GEM names | |
# | |
def search | |
@args.each do |gem| | |
begin | |
console_print get_info(gem) | |
rescue RestClient::ResourceNotFound | |
puts "No gem called \"#{gem.colorize(:red)}\" found.\n\n" | |
next | |
end | |
end | |
end | |
# Get GEMs information through rubygems.com API | |
# | |
def get_info(gem) | |
thrs = [] | |
thrs << Thread.new { @general = JSON.parse RestClient.get @endpoint + 'gems/' + gem + '.json' } | |
thrs << Thread.new { @versions = JSON.parse RestClient.get @endpoint + 'versions/' + gem + '.json' } | |
thrs.each(&:join) | |
{ general: @general, versions: @versions } | |
end | |
# Pretty print information from GEMs | |
# | |
def console_print(data) | |
puts [ | |
"#{data[:general]['name'].colorize(:yellow).bold} - #{data[:general]['version'].colorize(:green)} (#{Date.parse(data[:versions].first['built_at']).strftime('%d %B %Y').colorize(:green)}):", | |
word_wrap(data[:general]['info']).to_s, | |
"\t[#{data[:general]['source_code_uri'] || data[:general]['homepage_uri']}]" | |
].join("\n") | |
puts "\n" | |
end | |
# Wrap long lines and preappend tabs | |
# | |
def word_wrap(text, options = {}) | |
line_width = options.fetch(:line_width, 80) | |
line = text.split("\n").map(&:strip).join(' ') | |
line.length > line_width ? "\t" + line.gsub(/(.{1,#{line_width}})(\s+|$)/, "\t\\1\n").strip : "\t" + line | |
end | |
end | |
GemInfo.new(ARGV).search |
Author
arashm
commented
Aug 5, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment