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']
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With