2

Is there a way to tell which port a Rails application (or a generic Rack app) is running on in an initializer ?

I would like to be able to load a different configuration based on the port or the host name, in order to connect to a host-specific FaceBook application.

I'm using Rails 2.3.5.

Singleton
  • 3,701
  • 3
  • 24
  • 37
zoli
  • 469
  • 6
  • 17
  • 1
    If you don't find any solutions you should try this out http://stackoverflow.com/questions/1554267/how-to-find-the-local-port-a-rails-instance-is-running-on/1554523#1554523. – vise Nov 28 '10 at 11:16
  • Yup, getting the port from the request is pretty straightforward, but in the initializer I don't have any requests. I'm looking for something similar to what's mentioned in linked question: Sinatra::Application.port, but for Rails, not Sinatra. – zoli Nov 28 '10 at 18:59
  • More general question that does not require initializer: http://stackoverflow.com/questions/1554267/how-to-find-the-local-port-a-rails-instance-is-running-on (and as such has answers for both controllers and initializers) – Ciro Santilli OurBigBook.com Oct 09 '14 at 20:31

3 Answers3

2

This is not very clean but this is a way you can get the port you declared when calling :
rails server -p portnumber
wherever you want in your application (for rails 3).

Here is my scripts/rails.rb file :

#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" 
# with Rails 3 gems installed from the root of your application.
ENV['PORT']=ARGV[3]
APP_PATH = File.expand_path('../../config/application',  __FILE__)
require File.expand_path('../../config/boot',  __FILE__)
require 'rails/commands'

Then whenever you want to get the port number of your server, all you need to do is call ENV['PORT'].

jules testard
  • 193
  • 1
  • 9
2

You can call Rails::Server.new.options[:Port] to get the port that your Rails server is running on. This will parse the -p arg from your rails server command, or default to port 3000.

ndbroadbent
  • 13,513
  • 3
  • 56
  • 85
  • 2
    I'm getting uninitialized constant `Rails::Server` when I try to do this in my Rails 3.2 app. – Andrew May 11 '15 at 20:00
1

Based on the lack of answers here and this thread on rubyforum: http://www.ruby-forum.com/topic/196017#new , I think that there probably isn't a standard way to tell the port.

zoli
  • 469
  • 6
  • 17