7

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?

js_
  • 4,671
  • 6
  • 44
  • 61

3 Answers3

15

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à.

Mark Thomas
  • 37,131
  • 11
  • 74
  • 101
  • thanks. I dont know `sinatra` is installed to my server already. Im not allowed to install anything to my server. – js_ Jul 15 '11 at 02:20
12

You need the array request.env

request.env['REMOTE_ADDR']:

dhulihan
  • 11,053
  • 9
  • 40
  • 45
timaschew
  • 16,254
  • 6
  • 61
  • 78
  • Thanks. I tried google but i couldnt find them. About PHP, i always can easily find what i want to know with google. I think information about ruby is difficult to search. Thanks for introducing the nice website! – js_ Jul 15 '11 at 01:38
  • can i use `request.env` in `just ruby` not in `ruby on rails`? – js_ Jul 15 '11 at 01:42
  • 1
    "can i use request.env in just ruby not in ruby on rails? " No, `request` won't exist as an object. Your best bet for simple exploration is the answer @Mark Thomas gave, or use Ruby's `CGI` library and write a simple CGI that will run under Apache or nginx. – the Tin Man Jul 15 '11 at 02:22
  • 1
    @theTinMan I serched again with the keyword `cgi` you told me. And i found i can get the information from `ENV['REMOTE_ADDR']`, `ENV['HTTP_REFERER']`, `ENV['HTTP_USER_AGENT']`. Thank you. – js_ Jul 19 '11 at 08:39
  • Yes, those are standard environment settings defined by the HTTPd when calling your code as a CGI. If you're not familiar with that protocol it would be good to study up. It's the basis for all things web. – the Tin Man Jul 19 '11 at 18:13
2

I'm assuming you by ruby you mean ruby on rails, the following link shows you how to access them:

http://techoctave.com/c7/posts/25-rails-request-environment-variables

Jimmy Baker
  • 3,215
  • 1
  • 24
  • 26
  • thanks. but i meant ruby by ruby! im a beginner of ruby. and i just wanna make a simple logging program. – js_ Jul 15 '11 at 01:25