Ruby Gems
Gem Management
Installing and managing gems
# Install
gem install httparty
gem install nokogiri -v 1.15.0 # specific version
# List and search
gem list --local httparty
gem search ^net-
# Info and paths
gem info httparty
gem which httparty
# Update and cleanup
gem update httparty
gem cleanup # remove old versions
Bundler
Gemfile
source "https://rubygems.org"
ruby "~> 3.2"
gem "httparty", "~> 0.21" # >= 0.21.0, < 1.0
gem "net-ssh", ">= 7.0"
gem "colorize", require: false
group :development do
gem "rubocop"
gem "pry"
end
group :test do
gem "rspec"
end
Bundler commands
bundle init # create Gemfile
bundle install # install deps
bundle exec ruby script.rb # run in context
bundle update httparty # update one gem
bundle info httparty
Version constraints
gem "foo", "1.2.3" # exactly 1.2.3
gem "foo", ">= 1.2" # 1.2 or higher
gem "foo", "~> 1.2" # >= 1.2.0, < 2.0 (pessimistic)
gem "foo", "~> 1.2.3" # >= 1.2.3, < 1.3.0
Useful Gems for Infrastructure
Network and sysadmin gems
# HTTP
require "httparty"
response = HTTParty.get("https://api.example.com/status",
headers: { "Authorization" => "Bearer #{token}" },
timeout: 10
)
puts response.code
puts response.parsed_response
# SSH
require "net/ssh"
Net::SSH.start("10.50.1.40", "admin", password: pw) do |ssh|
output = ssh.exec!("show version")
puts output
end
# JSON (stdlib)
require "json"
data = JSON.parse(File.read("config.json"))
File.write("out.json", JSON.pretty_generate(data))