1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Beginners Guide to CGI Programming in Ruby

Discussion in 'Ruby on Rails' started by pradeep, Jun 13, 2013.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    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:
    #!/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:
    #!/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:
    #!/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:
    #!/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.
     
    coderzone and shabbir like this.

Share This Page