Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby equivalent of PHP's $_GET

What is the bare minimum I need to require in Ruby (not Rails or any other framework) to easily obtain request data like GETs?

I would like to avoid having to use ruby on rails or any other framework to get this data, so the ideal answer wouldn't have a framework dependency.

My current setup has a ruby file (script) in a cgi-bin on apache (site.com/script)

#!/usr/bin/env ruby

# bare minimum to output content
puts "Content-type: text/html"
puts

puts "it works!" #works fine.

# how would I obtain request data like GET parameters here
# for a url like site.com/script?hi=there
# in PHP, I would $_GET['hi']
like image 425
tester Avatar asked Dec 16 '22 18:12

tester


2 Answers

Ah, solved my problem using the CGI class.

http://www.ruby-doc.org/stdlib-1.9.3/libdoc/cgi/rdoc/CGI.html

require 'cgi'

cgi = CGI.new

cgi.params.each do |key, val|
   puts key
   puts val
end

so site.com/script?hi=there would output hi\nthere

like image 148
tester Avatar answered Dec 18 '22 07:12

tester


Please don't do this without a framework. There are some super lightweight ones like Sinatra that do as little as possible to ensure you have the support you need to do this correctly. CGI died in the 1990s and doesn't need to come back now.

To write a Sinatra application you basically define a method, then deploy it to your server. Sure, you may grumble about how much work that is, but if you don't have a proper deployment procedure you're in trouble before you even start.

Ruby has a lot of infrastructure built up around things like Rack that hook into Apache through modules like Passenger that do a lot more than cgi-bin ever did without all the risks associated with it.

A typical Sinatra app looks like:

get '/example/:id' do
  "Example #{params[:id]}!"
end

There's really nothing to it and it ends up being a lot less work than the old CGI way.

like image 27
tadman Avatar answered Dec 18 '22 07:12

tadman