Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

ruby - Sinatra configuring environments on the fly

I have successfull written a little Sinatra application and already successfully deployed it on heroku.

However I want to run that application in development mode on my local computer and I want to have it production mode on heroku once I push it to the remote repository.

Currently I can achieve either one of thos options. When I change my config.ru to the following values:

require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require "./calc.rb"

enable :logging
set :environment, :development
set :port, 4567

I'm able to run it locally (on port 4567) via ruby config.ru. When I change the config.ru to this:

require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
require "./calc.rb"

enable :logging
set :environment, :production
set :port, 4567
run Sinatra::Application

I'm able to get it to run on Heroku (on port 80).

But I can not use the same configuration for both development and production.

I would like to have something like:

ruby config.ru dev for development and ruby config.ru for production.

Additional information:

When I try to run the production config.ru on my local machine I get:

$ ruby config.ru
(eval):2:in `method_missing': undefined method `run' for main:Object (NoMethodError)
        from (eval):4:in `__send__'
        from (eval):4:in `method_missing'
        from config.ru:10
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
C:>type tmp.ru
require 'sinatra'
configure(:production){  p "I'm production" }
configure(:development){ p "I'mma dev mode" }
configure(:sassycustom){ p "I'mma own mode" }
exit!

C:>rackup tmp.ru
"I'mma dev mode"

C:>rackup -E development tmp.ru
"I'mma dev mode"

C:>rackup -E production tmp.ru
"I'm production"

C:>rackup -E sassycustom tmp.ru
"I'mma own mode"

C:>rackup -E notdefined tmp.ru

If you don't specify an environment, development is used by default. You can specify any environment name you want, though 'production' is very common. If you specify an environment that you don't configure, no configuration block will match. (It might be a mistake on your part, but it's not an error caught by the code.)

Note that the Sinatra documentation says that setting RACK_ENV environment variable will be used if available. This used to not work, but some time in the last few years it has been fixed!

If, for example, you can set an environment variable for your service, you can control the mode.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...