So I would like my Rails app instances to register themselves on a \"I\'m up\" kind of thing I\'m playing with, and I\'d like it to be able to mention what local port it\'s
You can call Rails::Server.new.options[:Port]
to get the port that your Rails server is running on. This will parse the -p 3001
args from your rails server
command, or default to port 3000
.
Building on the other answers (which saved my bacon!), I expanded this to give sane fallbacks:
In development:
port = Rails::Server::Options.new.parse!(ARGV)[:Port] || 3000 rescue 3000
In all other env's:
port = Rails::Server::Options.new.parse!(ARGV)[:Port] || 80 rescue 80
The rescue 80
covers you if you're running rails console
. Otherwise, it raises NameError: uninitialized constant Rails::Server
. (Maybe also early in initializers? I forget...)
The || 80
covers you if no -p option is given to server. Otherwise you get nil.
From inside any controller action, check the content of request.port, thus:
class SomeController < ApplicationController
def some_action
raise "I'm running on port #{request.port}."
end
end
For Rails 5.1 development server.
if Rack::Server.new.options[:Port] != 9292 # rals s -p PORT
local_port = Rack::Server.new.options[:Port]
else
local_port = (ENV['PORT'] || '3000').to_i # ENV['PORT'] for foreman
end
I played around with this a bit, and this might be the best solution for Rails 5.1:
Rails::Server::Options.new.parse!(ARGV)[:Port]
Two ways.
If you're responding to a request in a controller or view, use the request object:
request.port
If you're in an initialiser and don't have access to the request object use the server options hash:
Rails::Server.new.options[:Port]