使用 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