Rails 4: use a different server port depending on the environment

I am trying to automate the configuration of my rails application, and I want to be able to run the application without specifying a port, since I would like it to be selected depending on the environment.

In particular (something simple to start with) to run the application on port 3000, if the environment is production, on port 3500 otherwise.

So, after this answer, I added the following to the boot.rb file:

require 'rails/commands/server'

module DefaultOptions
  def default_options
    super.merge!(Port: Rails.env.production? ? 3000 : 3500)
  end
end

Rails::Server.send(:prepend, DefaultOptions)

Unfortunately, I am doing something wrong, because this is the result when I run rails s:

/home/luca/projects/ads_manager/config/boot.rb:10:in `default_options': undefined method `env' for Rails:Module (NoMethodError)
    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/server.rb:287:in `parse_options'
    from /usr/local/lib/ruby/gems/2.0.0/gems/rack-1.5.2/lib/rack/server.rb:184:in `options'
    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.0.0/lib/rails/commands/server.rb:58:in `set_environment'
    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.0.0/lib/rails/commands/server.rb:42:in `initialize'
    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.0.0/lib/rails/commands.rb:73:in `new'
    from /usr/local/lib/ruby/gems/2.0.0/gems/railties-4.0.0/lib/rails/commands.rb:73:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

Any idea why Rails.env is not available?

Alternatives to get the same result are more than welcome.

+4
3

* NIX,

export RAILS_ENV=production

.. , , .bashrc

.

boot.rb ENV['RAILS_ENV'] Rails.env

, .

+2

, Rails.env.production? ENV["RAILS_ENV"] != "production", :) :

require 'rails/commands/server'

module DefaultOptions
  def default_options
    super.merge!(Port: ENV["RAILS_ENV"] == "production" ? 3000 : 3500)
  end
end

Rails::Server.send(:prepend, DefaultOptions)
+2

Rails.env , ENV [ "RAILS_ENV" ]?

+1

All Articles