使用 Gemfile 和 Bundler

Gemfile 是在应用程序中组织依赖项的标准方法。一个基本的 Gemfile 将如下所示:

source 'https://rubygems.org'

gem 'rack'
gem 'sinatra'
gem 'uglifier'

你可以按如下方式指定所需的 gem 版本:

# Match except on point release. Use only 1.5.X
gem 'rack', '~>1.5.2'
# Use a specific version.
gem 'sinatra', '1.4.7'
# Use at least a version or anything greater.
gem 'uglifier', '>= 1.3.0'

你也可以直接从 git repo 中提取宝石:

# pull a gem from github
gem 'sinatra', git: 'https://github.com/sinatra/sinatra.git'
# you can specify a sha
gem 'sinatra', git: 'https://github.com/sinatra/sinatra.git', sha: '30d4fb468fd1d6373f82127d845b153f17b54c51'
# you can also specify a branch, though this is often unsafe
gem 'sinatra', git: 'https://github.com/sinatra/sinatra.git', branch: 'master'

你还可以根据宝石的用途对宝石进行分组。例如:

group :development, :test do
    # This gem is only available in dev and test, not production.
    gem 'byebug'
end

如果应用程序需要能够在多个平台上运行,你可以指定运行某些 gems 的平台。例如:

platform :jruby do
  gem 'activerecord-jdbc-adapter'
  gem 'jdbc-postgres'
end

platform :ruby do
  gem 'pg'
end

要从 Gemfile 安装所有 gem,请执行以下操作:

gem install bundler
bundle install