How to get ip address, referer, and user agent in ruby?

js_ picture js_ · Jul 15, 2011 · Viewed 8.6k times · Source

I want to log user's ip address, referer, and user agent.
In PHP, I can get them from the following variables:

$_SERVER['REMOTE_ADDR']
$_SERVER['HTTP_REFERER']
$_SERVER['HTTP_USER_AGENT']

How to get them in ruby?

Answer

Mark Thomas picture Mark Thomas · Jul 15, 2011

PHP is embedded in a web server. Ruby is a general-purpose language: if you need a web server context, you'll have to install it yourself. Fortunately, it's easy.

One of the easiest ways to get started is with Sinatra. Install the gem:

gem install sinatra

Then create myapp.rb:

require 'sinatra'

get '/' do
    request.user_agent
end

Start up the web server:

ruby -rubygems myapp.rb

Visit Sinatra's default URL: http://localhost:4567/

Et voilà.