Question

I'm trying to automate the configuration of my rails application and I want to be able to start the app without specifying the port, as I would like it to be chosen depending on the environment.

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

So, following this answer, I've added the following to my 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'm doing something wrong, because this is the output 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 obtain the same result are more than welcome indeed.

Était-ce utile?

La solution

If you are using *NIX systems, you can try the following

In your terminal run the command below

export RAILS_ENV=production

NOTE: This will set the environment to production temporarily, if you need this permanently, add this to your .bashrc file

And then start your application server.

Inside the boot.rb file, use ENV['RAILS_ENV'] instead of Rails.env

Hope this helps.

Autres conseils

I would tried your solution just changing the Rails.env.production?to ENV["RAILS_ENV"] != "production" and it works :) So:

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)

Rails.env is set later during the rails boot process, can you try checking ENV["RAILS_ENV"] instead?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top