How to find the local port a rails instance is running on?

前端 未结 6 556
滥情空心
滥情空心 2020-11-30 12:23

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

相关标签:
6条回答
  • 2020-11-30 12:42

    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.

    0 讨论(0)
  • 2020-11-30 12:49

    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.

    0 讨论(0)
  • 2020-11-30 12:52

    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
    
    0 讨论(0)
  • 2020-11-30 12:53

    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
    
    0 讨论(0)
  • 2020-11-30 12:55

    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]
    
    0 讨论(0)
  • 2020-11-30 13:01

    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]
    
    0 讨论(0)
提交回复
热议问题