2024-07-08
The core function of gem is installing gems. The simplest form uses the install command followed by the gem’s name:
gem install railsThis command downloads and installs the Rails framework. If you need a specific version, use the -v or --version flag:
gem install rails -v 7.0.4You can install multiple gems simultaneously:
gem install sinatra jsonFor gems requiring specific system dependencies (like native extensions), you might encounter compilation errors. In such cases, ensure you have the necessary build tools (like make and gcc) installed. On Debian/Ubuntu systems:
sudo apt-get update
sudo apt-get install build-essentialFor more complex dependencies, you might need to use a Gemfile (more on this later).
To see what gems you have installed, use the list command:
gem listThis displays a list of all installed gems. To search for a specific gem, use the search command:
gem search railsThis will show all gems matching “rails” in their name or description.
Keeping your gems up-to-date is important for security and access to new features. To update a single gem:
gem update railsTo update all installed gems:
gem update --systemThe --system flag updates the gem command itself to the latest version.
To remove a gem:
gem uninstall railsThis command removes the specified gem. If you have multiple versions installed, you will be prompted to choose which one to remove.
For larger projects, managing dependencies directly through the command line becomes cumbersome. Gemfiles offer a much cleaner approach. A Gemfile is a simple text file that lists all the gems your project requires. Here’s a basic example:
source 'https://rubygems.org'
gem 'rails', '~> 7.0'
gem 'rspec', '~> 3.0'This Gemfile specifies that the project requires Rails version 7.0 and Rspec version 3.0. The ~> operator denotes a version constraint (allowing minor version updates).
After creating a Gemfile, you need to use the bundle command (part of the Bundler gem) to install the dependencies:
bundle installBundler creates a Gemfile.lock file, which precisely defines the versions of all gems and their dependencies, ensuring consistent environments across different machines. This is important for collaborative projects.
By default, gem uses https://rubygems.org. However, you might need to use alternative sources. You can specify a source in your Gemfile or directly on the command line using the --source flag:
gem install my-gem --source https://my-private-repo.comThis example installs my-gem from a private repository.
This guide helps you navigate the world of Ruby gem management efficiently and effectively. Using these examples and further exploration, you can confidently manage your Ruby project’s dependencies.