learningtech
learningtech

Reputation: 33683

ruby equivalent of php's $_SERVER['REQUEST_URI']

I'm new to ruby. I have phusion-passenger installed with apache on Ubuntu. Is there a ruby equivalent for php's $_SERVER['REQUEST_URI'] or any of php's $_SERVER variables?

I am not using Sinatra or rails because i'm just trying to learn how to use ruby first.

Upvotes: 0

Views: 933

Answers (2)

spickermann
spickermann

Reputation: 106802

When you have a simple Rack server like this:

require 'rack'
require 'rack/server'

class EnvInspector
  def self.call(env)
    [200, {}, [env.inspect]]
  end
end

run EnvInspector

it would return you something like this that tells you all the keys in the env variable:

{
  "SERVER_SOFTWARE"=>"thin 1.4.1 codename Chromeo",
  "SERVER_NAME"=>"localhost",
  "rack.input"=>#<StringIO:0x007fa1bce039f8>,
  "rack.version"=>[1, 0],
  "rack.errors"=>#<IO:<STDERR>>,
  "rack.multithread"=>false,
  "rack.multiprocess"=>false,
  "rack.run_once"=>false,
  "REQUEST_METHOD"=>"GET",
  "REQUEST_PATH"=>"/favicon.ico",
  "PATH_INFO"=>"/favicon.ico",
  "REQUEST_URI"=>"/favicon.ico",
  "HTTP_VERSION"=>"HTTP/1.1",
  "HTTP_HOST"=>"localhost:8080",
  "HTTP_CONNECTION"=>"keep-alive",
  "HTTP_ACCEPT"=>"*/*",
  "HTTP_USER_AGENT"=>
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.47 Safari/536.11",
  "HTTP_ACCEPT_ENCODING"=>"gzip,deflate,sdch",
  "HTTP_ACCEPT_LANGUAGE"=>"en-US,en;q=0.8",
  "HTTP_ACCEPT_CHARSET"=>"ISO-8859-1,utf-8;q=0.7,*;q=0.3",
  "HTTP_COOKIE"=> "_gauges_unique_year=1;  _gauges_unique_month=1",
  "GATEWAY_INTERFACE"=>"CGI/1.2",
  "SERVER_PORT"=>"8080",
  "QUERY_STRING"=>"",
  "SERVER_PROTOCOL"=>"HTTP/1.1",
  "rack.url_scheme"=>"http",
  "SCRIPT_NAME"=>"",
  "REMOTE_ADDR"=>"127.0.0.1",
  "async.callback"=>#<Method: Thin::Connection#post_process>,
  "async.close"=>#<EventMachine::DefaultDeferrable:0x007fa1bce35b88
}

So env['REQUEST_URI'] would be the equivalent to php's $_SERVER['REQUEST_URI']

See http://hawkins.io/2012/07/rack_from_the_beginning/ for more examples how to use Rack.

Upvotes: 2

Matheus Moreira
Matheus Moreira

Reputation: 17020

I am not using Sinatra or rails because i'm just trying to learn how to use ruby first.

Ruby does not presume a web server. It is a general-purpose programming language that stands on its own. If you were using a web development framework, it would provide you with access to such data.

Both Rails and Sinatra use Rack, which uses a request object in order to access this data. The REQUEST_URI variable corresponds to the path including the query string; the fullpath method is used to access it:

# get '/articles'
request.fullpath # => '/articles'

# get '/articles?page=2'
request.fullpath # => '/articles?page=2'

The basic API is the same in all those frameworks. For reference:

Upvotes: 1

Related Questions