Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Ruby on Rails (http://www.go4expert.com/articles/ruby/)
-   -   Beginners Guide to CGI Programming in Ruby (http://www.go4expert.com/articles/beginners-guide-cgi-programming-ruby-t29690/)

pradeep 13Jun2013 15:28

Beginners Guide to CGI Programming in Ruby
 
CGI or Common Gateway Interface was created to server content over HTTP web servers using external scripting languages like Perl, Python, Ruby, or compiled binaries of C,C++, etc. Apache, the most popular web server and also others can be easily configured to run CGI scripts.

In this article we'll be looking at configuring Apache to run CGI scripts and writing simple CGI scripts in Ruby.

Configuring Apache



In the demo example I'll be using a directory rb-bin you may change this to whatever you like, cgi-bin is very popular and generally pre-configured. Do not forget to make all your scripts in the directory executable.

Add the following to Apache's config file, and then restart Apache.

Code:

ScriptAlias /rb-bin/

<Directory "/var/www/rb-bin">
   AllowOverride None
   Options ExecCGI
   Order allow,deny
   Allow from all
</Directory>



Basics of CGI Scripts



Unlike PHP, with Ruby you'll need to send your own headers. Headers and content of a HTTP response is separated by 2 newlines. Let's see how to send headers, let's write our first Ruby CGI script.

Code: Ruby

#!/usr/bin/ruby

print "Content-Type: text/html\n\n"
print "<h2>Hello World!</h2>"


Handling Form Data



For handling forms we'll need a Ruby library cgi, fortunately it comes bundled with Ruby. Here's how to read form values.

Code: Ruby

#!/usr/bin/ruby

require 'cgi'

cgi = CGI.new

name = cgi['Name']

puts cgi.header("type" => "text/html", "cache_control" => "no-cache, no-store")

puts "<h2>Hello #{name}</h2>"


In the above example we get the name & print it out.

Using Cookies



Cookies are accessed and created using the cgi library, so it's pretty simple. Let's try it with some code.

Code: Ruby

#!/usr/bin/ruby

require 'cgi'

cgi = CGI.new

## setting cookies
cookie1 = CGI::Cookie.new('name' => 'name','value' => 'Pradeep','expires' => Time.now + 3600)
cookie2 = CGI::Cookie.new('name' => 'city','value' => 'Kolkata','expires' => Time.now + 3600)

print cgi.header("cookie" => [cookie1,cookie2])


Reading cookies:
Code: Ruby

#!/usr/bin/ruby

require 'cgi'

cgi = CGI.new

print cgi.header()

name = cgi.cookies['name']

print "Name is #{name}"


Now you can get started with writing CGI scripts in Ruby. Enjoy.


All times are GMT +5.5. The time now is 07:18.