8

在我的本地机器上,我使用 mongrel 运行 rails。我有一些在启动时运行的东西,通过 config/initializers 中的一个文件,它用于puts告诉我它正在使用哪个数据库、用于发送电子邮件的内容以及其他一些信息。

当我在端口 3000、3001 和 3002 上运行 mongrel 集群时,我只想为端口 3000 上的 mongrel 执行此报告。因此,我需要将它包装在一个if块中,以测试当前运行的 mongrel 是哪个端口使用。谁能告诉我如何在我的代码中得到这个?

4

3 回答 3

2

在初始化器中,

puts Rails::Server.new.options[:Port]

可以报​​告您的端口。

于 2015-05-20T15:30:37.463 回答
1

好的,我正在回答我自己的问题,因为我是在设置赏金后才弄清楚的!

我可以使用. Process.pid然后我可以这样做ps afx | grep mongrel,这给了我这样的结果

 pid                                                                                 port
  |                                                                                    |
  V                                                                                    V
10761 pts/1    S      0:20  |   \_/usr/local/bin/ruby /path/to/mongrel_rails start -p 3000
10762 pts/1    S      0:18  |   \_/usr/local/bin/ruby /path/to/mongrel_rails start -p 3001
10763 pts/1    S+     0:23  |   \_/usr/local/bin/ruby /path/to/mongrel_rails start -p 3002

然后我可以 grep 获取 pid,并从匹配行中读取端口号,看看它是否为 3000。

所以,我的代码是

if `ps afx | grep mongrel_rails`.split("\n").detect{|line| line =~ /^#{Process.pid}.+\-p\s3000/}
  #this is a mongrel running on port 3000 - do the extra stuff
  ....
end

顺便说一句,如果有人能告诉我如何直接获得正在运行的杂种的端口,而无需通过ps afxProcess.pid我仍然会给你赏金:)

于 2015-05-20T14:48:59.010 回答
1

这在 2.2.2 中有效吗?

class SomeController < ApplicationController

  def index
        @port = request.port
  end
end
于 2015-05-24T20:41:35.633 回答