mongrel_rails - programatically report which port it's running on

183 Views Asked by At

On my local machine, i run rails with mongrel. I have some stuff which runs when it starts, via a file in config/initializers, which uses puts to tell me which database it's using, what is being used to send emails, and a few other bits of info.

When I run a cluster of mongrels, on ports 3000, 3001 and 3002, I only want to do this reporting stuff for the mongrel on port 3000. So, I need to wrap it in an if block which tests which port the currently running mongrel is using. Can anyone tell me how I can get this in my code?

3

There are 3 best solutions below

0
Max Williams On

Ok, i'm answering my own question as i just figured it out after setting a bounty!

I can get the pid of the currently running process with Process.pid. Then i can do ps afx | grep mongrel which gives me a result like this

 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

which i can then grep for the pid, and read the port number out of the matching line, and see if it's 3000.

So, my code is

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

BTW, if someone can tell me how to directly get the port of the running mongrel, without going via ps afx and Process.pid i'll still give you the bounty :)

10
Alper Karapınar On

in an initializer,

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

can report your port.

2
Joseph Freivald On

Does this work in 2.2.2?

class SomeController < ApplicationController

  def index
        @port = request.port
  end
end