home resources search newsjoinmembers: 6961
PHP Flash Java Ruby Windows Linux
Hiveminds's picture

Hiveminds | Sun, 2007-09-02 18:34  tags: , ,

Ruby is the interpreted scripting language for quick and easy object-oriented programming. It has many features to process text files and to do system management tasks as languages like Perl or Python do. Ruby is simple, straight-forward, extensible, and cross-platform portable language that has a syntax that is easy to understand. One of the strengths of Ruby is that it strives to be powerful but not complicated. Ruby has advantage over other OOP languages in that it can be used to code procedurally.

Here we show how to setup a windows development PC and a shared web host so you can start developing Ruby web applications in the same way you do PHP, embedded in HTML. Embedded Ruby, eRuby, is easy to learn and has features that make it more useful than other web scripting languages. Now you can use eRuby to create robust web applications and websites. This article will have you doing Ruby on the web in minutes.

Using Ruby on the web

What is eRuby?

eRuby is an extension to Ruby that allows you to use the power of Ruby and embed its code into HTML files. The way eRuby does this is by inversing the HTML code into print statements before sending the code on to be interpreted. Code in the HTML file is translated into a mix of single and multi-line commands. This is all sent to the Ruby CGI interpreter for processing.

Why not Ruby on Rails?

I could not very well write this without mentioning Ruby on Rails. Rails is probably the main reason that Ruby is becoming popular outside of Japan. But Rails is not the only way to use Ruby on the web. Rails also has many drawbacks in that it removes almost all of the ease of deployment of Ruby. Compared to the simple FTP upload of eRuby, deploying a Rails application is complicated, time consuming task and just not something that you will want to do on a repetative basis. Rails also is a lot of work if you just want to do a single webpage application that contains everything. Web hosting companies are also a large factor in using Rails. To do Rails properly you need to have ssh knowledge and be prepared to do some command line manipulation of files. The needs of Rails makes a shared hosting environment difficult to set up and administrate. One of the most troublesome of the Rails drawbacks for me and the reason that I decided to go with eRuby is the that Rails was taking up all my time with Rails problems and troubleshooting. I was learning a lot about using Rails but not much of the Ruby programming language. Someone suggested we go with CGI instead and while researching this we found eRuby.

eRuby is a much easier way of using, learning and getting the power of Ruby on to a website. With eRuby deployment is a easy as uploading your files to your web server. This is to say deploying an application or webpage is no harder in eRuby than it's counterparts like PHP or ASP. I honestly believe that if Ruby popularity is going to increase that eRuby will be the reason. Unlike Rails eRuby has a very shallow learning curve and does not require a lot of effort by web hosting companies to set up.

About this tutorial

In this tutorial I am going to assume a few things that require that you be familiar with the technology used. Although nothing in this writing is "geeks only" difficult it does require that you be familiar with the terminology or take the time to read a few paragraphs here and there from other resources. This tutorial is also geared towards Windows users and those wanting to do web development on Windows PCs. This tutorial is not intended to be a lesson on the Ruby language but on how to get started by setting up both a working development and production environment. Once you get your set up going you can go on to other articles covering how to do some useful application in Ruby

Setting up a development PC

Wampserver5

Is a free and opensource Apache webserver package for windows. The nice thing about wampserver is that it is a lightweight package and has a exceptionally friendly user interface. There are of course many other flavors of windows Apache packages. You are welcome to use one of those as long as you are confident that you can carry out the configurations needed to setup eRuby. Click on the executable and follow the instructions.

Ruby One-click installer

This is a single file that will install ruby on to your Windows computer. The only thing you have to do is click once or twice and wait. It contains the Ruby language itself, dozens of popular extensions and packages, a syntax-highlighting editor and execution environment, and a Windows help file that contains the full text of the book, Programming Ruby: The Pragmatic Programmer's Guide. Click on the executable and follow the instructions. Ruby is also set into the your Windows path so that you can run it from any directory.

eruby.exe( for set up on the localhost)

To interpret HTML pages that have Ruby code embedded in them you need a windows binary of the eRuby interpreter. You can either compile this binary yourself using minGW or you can use the pre-compiled file dowloadable from one of the minGW mirrors. Once you have downloaded the binary add the eruby.exe to the bin directory where you installed Ruby.

Apache 2 configuration

This tutorial is not geared towards the raw beginner so I will go straight to the instruction set for configuring the Apache web server. If you have never done this before then you may want to read up on it and train a bit before going further.

1. in httpd.conf add:

AddType application/x-httpd-eruby .rhtml
    #use your own path to eruby
    Action application/x-httpd-eruby "e:/usr/local/bin/eruby.exe"
    AddType application/x-httpd-cgi .rhtml
    #not really needed
    AddHandler cgi-script .cgi

2. add "+ExecCGI" directive to pertinent directories sections or add it in the global DocumentRoot(be warned thought, this allows executable cgis in ALL DocumentRoot an subdirs good for localhost but probably not smart for real servers).

3. You will also want to add in this directive which tells Apache where to look to get the file association. Normally a shebang is called for in the eRuby file. But since we want to get easy deployment getting rid of the shebang is necessary. Otherwise you will have change or remove the shebang before uploading your files to the shared host. Futher along in this tutorial you will see why this directive is needed but to save having to go back into http.conf and restarting Apache again we are going to do this now.

ScriptInterpreterSource "registry"

4. Besure to update the Directory index file list to reflect *.rhtml.


DirectoryIndex <b>index.rhtml</b> index.html index.htm

5. add as first line to the cgi files(*.rb,*.rhtml...)

#!f:/ruby/bin/eruby.exe ( this should be the path to Ruby on your PC )

Save this in docroot as eruby_test.rhtml, run it.


#!f:/ruby/bin/eruby.exe
<html>
 <head>
  <title>Welcome to eruby Test</title>
 </head>
<body>
<h2>eRuby test</h2>
<pre>
<%
    3.times {
        puts "Hello World"
    }
%>
</pre>
</body>
</html>

The CGI shebang

If you'll notice the test file code has a shebang path at the top of it. The shebang directive is used to control how Apache finds the interpreter used to run CGI scripts. Since eRuby is running as a CGI this is necessary. But when you are going to upload your *.rhtml files to your production webserver a shebang is not needed in most cases. This is going to depend on the servers configuration but I think in most scenarios you will be developing on Windows and the uploading the finished scripts to a Linux OS based web host. When you deploy to this server a shebang is not needed but for the purposes of testing we will leave this in place and then work on removing it later. The Apache web server uses the interpreter pointed to by the shebang line (first line, starting with #!) in the script. On Win32 systems this line usually looks like:

#!C:/ruby/bin/eruby.exe

or, if eruby is in the path, simply:

#!eruby

If changing the path of all of your development PC files before uploading to your shared hosting account is trivial then you might not want to concern yourself with the next section. But if you are planning on distributing your code then you will want to make it as user friendly and generic as possible. Below are the instructions for running CGI on Windows without using a shebang line in your files.

Configuring Windows and Apache 2

This next step is an advanced windows user procedure which is why I saved it for last. After you have tested the environment and had a little fun with some simple Ruby you will want to setup for deplyment to a shared host. Nothing special is needed for this but a windows configuration change is called for to allow your *.rhtml to run on the shared host unmodified. You want the script to run without using a shebang at the top. The previous http.conf setting for the directive

ScriptInterpreterSource "registry"

will cause the Windows Registry tree HKEY_CLASSES_ROOT to be searched using the script file extension (e.g., .rhtml, .rb, .rbx) as a search key. The command defined by the registry subkey Shell\ExecCGI\Command or, if it does not exist, by the subkey Shell\Open\Command is used to open the script file. If the registry keys cannot be found, Apache falls back to the behavior of the Script option.

In order for ScriptInterpreterSource Apache directive to work, you also need to add an entry to the Windows Registry so Apache will use Ruby to execute *.rhtml files. Go to start->run and in the input box write "regedit" to start the windows registry editor. Create a key HKEY_CLASSES_ROOT\.rhtml\Shell\ExecCGI\Command with the default value of the full path of eruby.exe. For example C:\ruby\bin\eruby.exe.

You can also create a registry execution file. Just copy the follwing to a notepad file and save it with the *.reg extension ex. "eruby_rhtml.reg". Clicking on the file will update the registry and give a popup about its install.

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\.rhtml\Shell\ExecCGI\Command]
@="C:\ruby\bin\eruby.exe"

After doing the above procedure remove the shebang line from your test file and run the script in the browser. If everything is okay then you will get the same output. If Apache cannot find a file association in the registry then it will throw an internal 500 error.

Security

Be careful when using ScriptInterpreterSource "registry" with ScriptAlias'ed directories, because Apache will try to execute every file within this directory. The Registry setting may cause undesired program calls on files which are typically not executed. For example, the default open command on .htm files on most Windows systems will execute Microsoft Internet Explorer, so any HTTP request for an .htm file existing within the script directory would start the browser in the background on the server. This is a good way to crash your system within a minute or so.

The option Registry-Strict which is new in Apache 2.0 does the same thing as Registry but uses only the subkey Shell\ExecCGI\Command. The ExecCGI key is not a common one. It must be configured manually in the windows registry and hence prevents accidental program calls on your system.

Setting up the shared host

.htaccess support on your web host

To gain access to the CGI executable on a shared web host you should use .htaccess. It is a simple thing and it allows you to control where eRuby can be used on the directory system.


    DirectoryIndex <b>index.rhtml</b> index.html index.htm
    AddHandler rubypage .rhtml
    Action rubypage /eruby.cgi

eruby.cgi ( for set up on the web host)

If your web host has eruby installed and you have access to ssh then you will only have to copy eruby from the server to your accounts root folder. When you copy the files from the folder it will auto-matically be renamed eruby.cgi


    $ cp local/bin/eruby public_html/cgi-bin/eruby

You can also compile your own eRuby and install it if your web host allows this on their servers. In most cases copying the web hosts file is best because you know that it is working and safe. But you may be in a situation where the web host has not installed eRuby but has nothing against you doing it yourself.


    $ cd ~
    $ wget http://www.modruby.net/archive/eruby-1.0.5.tar.gz
    $ tar zxvf eruby-1.0.5.tar.gz
    $ cd eruby-1.0.5
    $ ./configure.rb --prefix=$HOME/local && make && make install
    $ cd ~
    $ cp local/bin/eruby public_html/cgi-bin/eruby

Conclusion

Now that you have both a development computer and a web host environment that supports eRuby you can start taking advantage of the Ruby language. Let's go through a simple web application just to get a taste of what Ruby provides. A demo can be found here.


<html>
 <head>
  <title>Welcome to eruby Test</title>
 </head>
<body>
<h2>eRuby test</h2>
<%
# Require the CGI library
require 'cgi'
# New CGI object
cgi = CGI.new
# prepare trap for form variables
# there is an artifact space sent from an empty form field so to verify the field values have to be
# Stripped of whitespace and carriage returns (strip) so (empty) will work properly.
username = cgi['username'].strip
profession = cgi['profession'].strip
%>
      <form method="post">
        Please enter your username: <input type="text" name="username"><br>
        Please enter your profession: <input type="text" name="profession"><br>
        <input type="submit" value="Send">
      </form>
    <% if username.empty? # Print out the form asking for the username %>
      <p>Please test my first Ruby web application by entering your name in the text box.</p>
    <% else %>
      Thanks, <%= username %>!<br>
        <% if profession.empty? %>
            <p>So you are unemployed? Don't worry learn Ruby and you will have a job in no time.</p>
        <% else %>
        <p><%= profession %> sounds like a fun profession.</p>
    <% end %>
    <% end %>
</body>
</html>

Resources

Wampserver

Get it from here:

http://www.wampserver.com/en/index.php

Ruby one-click installer

Get it from here:

http://rubyforge.org/frs/?group_id=167

eRuby

If you are a wiz at using minGW or another windows compiler tool you can compile eruby yourself using the sources at http://modruby.net/ current: eruby-1.0.5.tar.gz a
pre-compiled binary can be found at the any of the minGW mirrors:

eruby zip
eruby tar

eruby.cgi

Getting this file can be a bit difficult if you do not have ssh access to your Linux server. You can also request that your web host copy it to your domain root or directory that you will be using eRuby. I have tried downloading add upload this file but this method is not dependable. The file is binary and very sensitive to changes in placement.


Happy Publishing!

Hiveminds's picture
This article brought to you by the Hiveminds Magazine - Staff. Contact us if you want to post an article or announcement anonymously
Thoughtbox - So what did you think?



a Visitor posted on: Mon, 2006-10-16 19:24.

Control Panel > Administrative Tools > Internet Information Services
Select your website and click Properties (toolbar, or Action>Properties, or via Right-click).
On "Home Directory" Tab click Configuration button on lower right
Click Add... button, click Browse... to locate eruby.exe, click Ok and add .rhtml on Extension, click Ok.
Click "Documents" tab, then Add... type index.rhtml then Ok and Ok again.
Voila! eRuby under IIS

a Visitor posted on: Fri, 2008-01-25 22:01.

Thank you for an informative article, it was very helpful, but the result is probably not what you intended.

 

>> Rails also has many drawbacks in that it removes almost all of the ease of deployment of Ruby. Compared to the simple FTP upload of eRuby, deploying a Rails application is complicated, time consuming task and just not something that you will want to do on a repetitive basis. <<

 

Thank you for dispelling any lingering doubts that I had about the usefulness of Ruby. Now I know for sure that I will not waste my time learning it. See this link for more about the subject:
oreillynet: 7 reasons I switched back

 

 

>> Ruby has advantage over other OOP languages in that it can be used to code procedurally. <<

er uh, ever heard of PHP ?

 

Codeslinger -- compsalot.com

Hiveminds posted on: Sun, 2008-01-27 15:15.

Well, yes Ruby is just another language like Perl or PHP not a holy grail. Rails is just a facilitator of good programming technic.

But the thing about Ruby is that it is was built using OOP guidelines and principles from the beginning. PHP on the other hand was not and is slowy adapting them now. With PHP 5.3 there will be a significant change in how OOP style programming will be done in PHP. But PHP will still not have the ease of use that Python, Ruby and C# provide out of the box.

Here is the problem with most that try Ruby, Rails. Those that try to build with Rails only discover the shortcomings of PHP in relation to Rails and not Ruby. Those that try .NET or Python have a better experience and gain more perspective because they are not blinded by a framework (although .NET is a framework it is not limited because of the CLR).

So when you say you want to give Ruby a shot then do just that. Stay away from Rails. Also try and program using something other than MVC. Do a fair comparison of Ruby vs. PHP using other patterns ( I recommend Matt Zandstra's _- PHP5 Objects, Patterns and Practice for ideas) and you will see the elegance of Ruby show.

a Visitor posted on: Tue, 2008-02-05 22:41.

This is great but needs a linux rewrite, most people use linuxin production for web....so showign us a-2-z on windows is useless.....how about a redo in linux?

Hiveminds posted on: Fri, 2008-02-08 13:06.

Setting up on a Mac is not too different from doing in in Linux. Here is a tutorial on how to set up eRuby on Mac OSX 10.4 tiger

eRuby on a Mac

a Visitor posted on: Thu, 2008-02-28 18:19.
> er uh, ever heard of PHP ?

Ruby > PHP in OOP.

ahamilton posted on: Tue, 2008-03-04 06:10.

There must be a spam bot making these stupid comments. A real person could not possibly have such low intelligence.

a Visitor posted on: Fri, 2008-04-11 11:32.

Maybe that should have been 'can be used to code functionally'?

a Visitor posted on: Tue, 2008-05-27 20:39.

Thanks for an excellent tutorial. I got your rhtml example to work, but not the cgi approach - all I get is 400 Bad Request. I would guess there's something that needs to be added to httpd.config or the registry?

Helen

Hiveminds posted on: Tue, 2008-05-27 22:29.

Something like a 400 error is hard to nail. My first thought is that there is another web servr running and is intercepting the request. If you are running this locally take a look at your server logs and check to make sure that the right server is getting the request.




 
CMS Comparison Matrix
 
Windows Adobe Flex Content Management Systems Web Developers Content Management Systems Drupal PHP

Newsletter

Get updates on Hiveminds services, articles and downloads by signing up for the newsletter.

Editor's choice

Some of the better articles, stories and tutorials found at Hiveminds.

Find more

Find more of Hiveminds articles, stories, tutorials and user comments by searching.




Picked links

Hand picked websites and articles from around the web that provide quality reading.