Rails Gemfile: use one line in development, anothe

2019-07-15 13:55发布

问题:

We run Unicorn on Heroku in production but use Webrick in development on a local machine. We are unable to install Unicorn on the local machine.

Is it possible to have Rails load the Unicorn gem only in production? Right now, our solution is to comment out the Unicorn gem when running the app locally and uncomment the gem when pushing to Heroku.

We're on Rails 3.2.12.

Gemfile:

source 'http://rubygems.org'

gem 'rails', '3.2.12'
gem 'jquery-rails'


# # =========================================================================================
# 
# #=========================================================================================
gem 'mongo'
gem 'mongo_mapper'
gem 'plucky'
gem 'bson_ext'
gem 'bson'
gem 'newrelic_rpm'
gem 'rpm_contrib'


# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails', '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'uglifier', '>= 1.0.3'
end

Thanks!

回答1:

Is it possible to have Rails load the Unicorn gem only in production? Right now, our solution is to comment out the Unicorn gem when running the app locally and uncomment the gem when pushing to Heroku.

Yes, it is possible by the use of groups in Gemfile. Update your Gemfile like follows for the unicorn gem in production only:

# Gemfile
group :production do 
  gem 'unicorn'
end

Since WEBrick is the default web server for rails apps, you wouldn't need to specify anything for development group.

Running bundle install after the Gemfile update will still install the production gems. This is definitely a good thing to do as you want to make sure the gems you are planning to use in production work correctly with your application from the development phase of project.

To skip installation of production group gems:

bundle install --without production

A point to be noted about the --without production option is that the subsequent calls to bundle install and bundle update are also going to skip installing and updating production gems. To disable this you'd need to remove the lineBUNDLE_WITHOUT: production from your app_root/.bundle/config:

# app_root/.bundle/config

BUNDLE_WITHOUT: production