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

前端 未结 6 561
滥情空心
滥情空心 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: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.

提交回复
热议问题