Thursday, December 14, 2006

Functional Testing in Rails that Requires Login

For RESTful authentication, there is a
login_as(user) method in AuthenticatedTestHelper module that sets the
current user
in the session from the user fixtures. This is under the lib directory.

In my functional test, I have:

def test_should_show_billing_profile_for_valid_login
login_as (:aaron)
get :show, :id =>
assert_response :success
assert_select "html:root>head>title", "BillingProfiles: show"

users.yml looks like this:

id: 1
login: quentin
salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd
crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test
created_at: <%= 5.days.ago.to_s :db %>
id: 2
login: aaron
salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd
crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test
created_at: <%= 1.days.ago.to_s :db %>

class BillingProfilesController < ApplicationController

before_filter :login_required

def show
@user = User.find(session[:user], :include => [:billing_profile])
@billing_profile = @user.billing_profile

respond_to do |format|
format.html # show.rhtml
format.xml { render :xml => @billing_profile.to_xml }

The problem was that I was using session[:user_id] in my controller
whereas the RESTful authentication
module is using session[:user] as shown below:

module AuthenticatedTestHelper
# Sets the current user in the session from the user fixtures.
def login_as(user)
@request.session[:user] = user ? users(user).id : nil

So I changed my controller code to use session[:user] and my tests now
pass! The plugin itself has the API to help you do the functional
testing. Very nice indeed.

Monday, December 04, 2006

Installing Sqlite3 on Mac OS 10.4

1. Install DarwinPorts, download DarwinPorts 1.3.2-archive.tar.gz, unzip it.
2. Copy unzipped folder to some location
3. cd to that location cd darwinports/base and run ./configure
4. make
5. sudo make install
6. Add export PATH=$PATH:/opt/local/bin to ~/.profile
7. Either logout of Mac or do source .profile
8. Run port sync
9. sudo port install rb-sqlite3
10.Run sqlite databasename in a shell. You will go to the sqlite command prompt.

You can now create tables and run sql queries. The advantage of this database is that it speeds up the testing during development. It is very fast.

Rails Cheat Sheets

1. Assert Select CheatSheet
2. Ruby on Rails CheatSheet
3. Textmate Rails CheatSheet
4. Scriptaculous CheatSheet
5. RJS Demystified
6. Form Helpers CheatSheet
7. Active Record Relationships CheatSheet
8. AJAX CheatSheet
9. Ruby on Rails Testing CheatSheet
10. TextMate CheatSheet for Rails Developers

Wednesday, November 29, 2006

Email validation plugin

1.Setup the Rails project in Subversion by following the Subversion Primer for Rails blog post.
2. Ran into problems while installing plugins and after reading the James Adams's plugin book, I found the solution, I had to do:

script/plugin install –o

to install the plugin.

I also looked at the test directory of the plugin and did the same assert in my unit test.

Tuesday, November 21, 2006

Restarting WEBrick using script

pid=$(ps -o pid,command | grep '\' | awk '{print $1}')
kill -9 $pid
ruby script/server

This script restarts the Webrick cleanly (doing CTRL+c does not seem to shutdown the server)

Save it in a file, Do a chmod +x and type the command: sh to run it.

Thursday, November 09, 2006

Rake Aborted! Migration Headache

If the migration is not working in AWDWR Rails examples. Remember that you must be on Edge Rails to make it work.

The Ruby Way, Ruby in a Nutshell and Rails Plugin Extending Rails Beyond the Core

The Ruby Way and Ruby in a Nutshell books arrived from Amazon today. I will post the review when I get a chance.

I also bought the "short cut" Rails Plugins by Addison Wesley, a 100 page pdf book. This book is a gem. More to come soon...

Ruby Interceptor

Beyond Java book had a good example of Interceptor in Ruby. It is like AOP, but is simpler.

1. Create an alias for the method that you want to intercept.
2. Define a new method with the same name as the old method
3. Delegate the call to the old method and add new code to do whatever you want in this method.

You basically open the class, intercept the calls to that method and add additional functionality to the method.

Tuesday, November 07, 2006

Head Rush AJAX

Very good book. Shows the big picture in a very easy to understand way. The concepts are well explained and brings any novice up to speed quickly. This book helped me to move on to study other materials like RJS Templates by OReilly.

Metaprogramming with Ruby

Ruby is a dynamic language. You can create classes and methods at runtime. This is metaprogramming. You can write code that writes code.

Example: Data format driving the code, CSV file with header at the top.

file: people.txt
"Smith, John", 35, 175, "5'10"
"Ford, Anne", 49, 142, "5'4"
"Taylor, Burt", 55, 173, "5'10"
"Zubrin, Candace", 23, 133, "5'6"

1. The code must not change when a new attribute is added to the existing file or if we are given a different file with different attribute names.
2. The header values such as name and age must be treated as attribute names.

Create a class with a name derived from the file name. First line of the file must have list of attribute names. Checks that can added are: Check the attribute name is a legal Ruby method name, badly formed and missing data.

Given the file name we can create a class from its contents. So:

class_name = File.basename(file_name,".txt").capitalize # Create the class name
# e.g. "foo.txt" => "Foo"
klass = Object.const_set(class_name,

Monday, November 06, 2006


Awesome Firefox extension, install the plugin and browse the scripts. I installed a script that blocks all Yahoo ads. No more annoying flashing ads in my email account. There are tons of useful scripts. One of the script I installed compares the price of Amazon books with other online stores.

Also, install the scripts one at a time. Install a script and use your browser for sometime and see if everything is fine. This is important because I installed lot of scripts on my laptop and now one of the script is opening up all the links in a new window!

If you install it one at a time, you can easily find out which script is causing the problem.

Metaprogramming - Write code that generates code


1. Open-Closed principle - Programs that need to pre-generate data tables
2. Mini-language to handle boilerplate code - Programs that have a lot of boilerplate code that cannot be abstracted into functions
3. Programs using techniques that are overly verbose in the language you are writing them in

The art of metaprogramming, Part 1: Introduction to metaprogramming - Jonathan Bartlett

Excellent article on Metaprogramming with Ruby

Sunday, November 05, 2006

How to load fixtures after tables and indexes are created.

Steve Hammond's Blog had this interesting tip:

Can we tell a migration to load the fixtures after it has created the tables and indexes?

Fixtures.create_fixtures('test/fixtures', %w{archetypes tile_types tiles})

The first argument is the directory where the fixtures can be found and the second is an array of fixtures to be loaded. This will load the fixtures into the environment where the fixture is being run. As usual Rails will figure out YAML vs. csv fixtures for you

Thursday, November 02, 2006

Using the Ruby Development Tools plug-in for Eclipse

This plugin allows debugging, check it out.

Resources - Domain Specific Languages in Ruby

1. Seeing MetaClasses Clearly

2. MetaprogrammingWriterTopia by Bill Katz

3. Domain Languages as Rails Plug-Ins: Steve Hammond

4. Meta Rails - Stuart Halloway

5. Neal Ford - Language Oriented Programming Keynote

Script to Setup Rails in Subversion

The following notes is based on the thread Create a rails project skeleton and import and checkout from svn all at once!

1. Create your repository on the server

2. Put the source code in a file called ‘svnrails’ inside of a directory that’s in $PATH. I have mine in /usr/local/bin (where the svn, rails and ruby binaries like to do their thing)

3. This will work with any kind of svn repository (ie. file:///, svn://, http://)

4. If your repository requires authorization, you will be prompted when necessary.

5. I haven’t built any error handling into this, so use the ol’ “measure twice and cut once” technique when typing this command

6. Type the command without arguments for usage

7. You have the option of not creating the /trunk, etc. directories in the repository; and the default command looks like this:

svnrails myapp svn://myserver

8. As long as you’ve created a repository called myapp on the subversion server, this script will automatically import your project into it. In other words, it defaults the name of the repository to be the same as the name of the app; this can be overriden (sensible defaults and all that).

9. Ignores various files in the repository as per the rails wiki

You can find the code here

Doubt: Does this require any changes for Edge Rails?

Wednesday, November 01, 2006

ZenTest Notes

To use unit_diff, pipe normal tests through it:

$ ruby ./TestZenTest.rb | unit_diff


pressing Ctrl-c once reruns the tests immediately. Pressing the key combination twice terminates autotest.

$ autotest -help


-v Be verbose.
Prints files that autotest doesn't know how to map to tests.

-rails Force rails mode.
Rails will be automatically detected by the presence of config/environment.rb. Use this if you don't have one.

You may need to run 'rake db:test:prepare' before
starting autotest on a rails project.

-vcs=NAME Version control system to update.
Autotest will automatically update every vcstime
Autotest understands Perforce (p4), CVS (cvs) and
Subversion (svn).

-vcstime=N Update source control every N seconds.
Defaults to every five minutes (300 seconds).

ZenTest MyProject.rb TestMyProject.rb > missing.rb

./TestMyProject.rb | unit_diff


multiruby ./TestMyProject.rb

(and other stuff for Test::Rails)

How to use ZenTest on Rails?

ZenTest Documentation

Resources for Testing Ruby on Rails

1. A Guide to Testing the Rails
2. Test First Programming with Ruby
3. Ruby on Rails Testing Cheat Sheet
4. Testing Rails Apps - Mike Clark
5. Test Your Helpers
6. Testing Rails controllers communicating with external web services
7. Test Driven Designg Using ZenTest
8. A Rails Testing Tutorial
9. How to Use ZenTest with Ruby
10. Autotest Rails
11. Testing Rails Apps
12. Selenium on Rails
13. Running Your Rails App Headless
14. YAML Fixtures
15. Testing RJS Templates
16. RJS Assertions
17. 2005 Rubyconf ZenTest Movies - Ryan Davis
18. ZenTest Blog
19. Test-First development

Tuesday, October 31, 2006

Collecting email addesses on your website

In email marketing it is important to use the names of your subscribers to establish connection. When users fillout the forms to subscribe to your list some of them will be lazy and enter names in all lowercase. When you merge the fields during mailing your newsletter it can be very tedious to clean up the database.

In Rails, you can cleanup the name fields as follows:

test = "StRrIPPed TEst"

This will create a string : "Strripped Test"

Remember that Rails has opened the existing string class and added these methods to it. So to find out the methods that are available:

~/work/testr > ./script/console
(From the Rails project directory)

> test.methods

will give you list of all available methods.

Subversion Setup for Edge Rails

The following steps are customized for my needs from the Subversion Primer for Rails Project.

1. mkdir ~/svn

2. svnadmin create --fs-type=fsfs ~/svn/pinkatio

pinkatio is the name of the Rails project

3. REPOS=file:///Users/balaparanj/svn/pinkatio

For some reason the `pwd' embedded inside the file:// does not work.

4. svn mkdir --message="Initial project layout" $REPOS/trunk $REPOS/tags $REPOS/branches

5. ~/work/pinkatio > rails pinkatio

6. ~/work/pinkatio > svn checkout $REPOS/trunk .

7. ~/work/pinkatio > svn add --force .

8. ~/work/pinkatio > svn mkdir db/migrate tmp

Ignore any error message for tmp directory.

9. ~/work/pinkatio > svn revert log/*

10. ~/work/pinkatio > svn propset svn:ignore "*.log" log

11. ~/work/pinkatio > svn propset svn:ignore "*" tmp

12. ~/work/pinkatio > svn propset svn:ignore "*doc" doc

13. ~/work/pinkatio > svn propset svn:executable "*" `find script -type f | grep -v '.svn'` public/dispatch.*

14. ~/work/pinkatio > svn commit --message="New Rails project"

15. ~/work/pinkatio > svn propset svn:externals "rails" vendor

16. ~/work/pinkatio > svn update vendor

17. ~/work/pinkatio > yes | rails .

18. ~/work/pinkatio > svn commit --message="Living on the Edge - set svn:externals on vendor / for Rails"

I skipped the steps to delete and remove the index.html from svn because the command yes | rails . undoes that step.


1. How to use Rails with Subversion
2. Create a Rails project skeleton and import and checkout from SVN all at once!

Rubyisms in Rails Book Review

I just finished reading this book. This book has the best explanation on symbols. It does a good job of explaining duck typing, blocks and metaprogramming. The topics under metaprogramming are very easy to understand, they are reflection, message sending and method missing.

I found it easier to understand because it shows snippets of Java code to show how the problem can be solved and then gives the Ruby equivalent.

It does not explain very well or go deeper on the DSL topic. This could have doubled the size of the book easily.

Thursday, October 26, 2006

Rails Secure Plugin and Google Checkout Plugin for Rails

secure_action is a ruby on rails plugin which makes it easy to defend your site against assumed logged in attacks.

To install, check out the code in your RAILS_ROOT/vendor/plugins/ directory and follow the instructions in the README:

svn checkout secure-action-plugin

Interesting article from a developer

svn checkout checkout-on-rails

Rails RESTful Authentication Plugin Part II

1. Include the line: map.connect '/', :controller => "sessions", :action => 'index'
in routes.rb
Browse the source code you will see that after login and logout the action methods route to '/', so the above definition will load the index.rhtml for the sessions_controller

2. In the sessions_controller.rb add the following method:
def index
3. Create a index.rhtml file in the views/sessions directory, include the following lines in the file:

<% if flash[:notice] -%>
<%= flash[:notice] %>

<% end -%>

Now when you login or logout, you will the message "You are logged in" and "You have been logged out message".

4. You can also uncomment the code for remember me functionality in the rhtml file. This will provide a check box that allows the user to login without entering the username and password.

Wednesday, October 25, 2006

How to setup RESTful Authentication

The following steps are tested on Mac OS 10.4.8

1. Create the Rails application: rails testr

2. Cd to testr directory. You need Rails 1.2 for this plugin, so:
rake rails:freeze:edge

3. Install the plugin: ruby script/plugin install
(the command must be in one line)

4. Add the resouces in the config/routes.rb file (just below the first line):

map.resources :users, :sessions
map.signup '/signup', :controller => 'users', :action => 'new'
map.login '/login', :controller => 'sessions', :action => 'new'
map.logout '/logout', :controller => 'sessions', :action => 'destroy'

I also commented out the last line (default Rails 1.1 style routing).

5. Generate the migrations: ./script/generate authenticated user sessions

6. Generate mailer: ./script/generate authenticated_mailer user

7. Run mysql server

8. Specify the database password in database.yml file in config directory

9. Create testr_development database (Use CocoaSQL, YourSQL, MySQL Query Browser or command line)

10. Cd to db/migrate directory and run: rake db:migrate

11. Start the webserver: $testr > ./script/server

12. Point the browser to http://localhost:3000/signup

13. View the output of the signup process in the server console, you will see SQL insert statement.

14. Check the user table to see the newly created record.

15. Go to http://localhost:3000/login and http://localhost:3000/logout and play with the application.

I am getting sqlsock error in RailsLive CD environment. It has MySQL server 5.0. My mac has MySQL server 4.0 and it does not have any problems.

Monday, October 23, 2006

Getting Real - 37 SIgnals book

Last night I bought the "Getting Real" book from 37 signals and I finished
reading it. Here is the process that they have used with success:

1. Draw html mock-ups using paper and pencil. Easy to change and the cost of
throwing it away is negligible.
2. Create static html mockup for your site. Get feedback and make any
3. Code the most essential feature. Less is more. (They talk about
"Epicenter Design")
4. Release. Say no to all the features requested by customer. Incorporate
only those that align with the "Vision" for your software and is requested
by most of the customers.

In general there is no artifacts such as documentation, specification or
diagrams created during the product development. They are a waste of time
since no one can agree on issues. It is easier to know what we are building
and refine it when we play with the real thing.

It has helped me to think clearly and I have gained so much from this book.
I now have a blueprint for building a successful online business. I highly
recommend this book.

Rails Goodies

Agile Web Development with Rails covers the Model, View and Controller part of the Rails framework very throughly.

It falls short in AJAX and WebServices. OReilly's $10 pdf book on RJS and Webservices really rocks.

Money Train is another pdf book which is basically based on the RailsConf 2006 presentation. It contains very practical tips on Rails development.

Also $100 subscription to the RailsConf 2006 online video is not worth it. The quality of some of the videos is poor. The website has problems streaming the content. It drops the connection several times. Very frustrating experience. Half of the recordings have no video. I got the password for the site after 4 days.

There are some good presentations, I liked the DSL presentations. Google Reader is great, I subscribed for all the Rails related blogs and sites. It saved me money, I decided not to buy the RSS reader for Mac OS.

Thursday, October 19, 2006

Linux RailsLiveCD and VMWare Player on Windows

Booting the RailsLiveCD from the CD was problematic. Changed the BIOS setting to boot from CD, still no luck. Fortunately it is even better with VMWare player. It is free. This method also allows you to run both windows and Linux at the same time.

1. Download and install the free VMware player.
2. Download and install the generic virtual machine.
3. Rename the RailsLiveCD iso file to livecd.iso. Move this file to the same directory as the generic virtual machine.
4. Open the vmx file in the VMware player and enjoy.

This blog is more descriptive.

Tuesday, July 18, 2006

Subversion svn server

Pragmmatic Version Control - using Subversion is a very easy to read book. It makes it easy to learn about Subversion. This book will prepare you to move on to the free book on Subversion available at redbean. Search Rails mailing list for the actual link.

The reason for this post is that this explains about how to use the svn server to connect to your repository. I am running Subversion on my Powerbook. The IP address changes due to my ISP. In order to give a host name to my Mac I followed the instructions on the site Give your Mac OS X computer a hostname with DynDNS

It was easy to sign up for the account. However the article does not provide the following tips:

The website design makes it very difficult to navigate. Find the link for Home Solutions on the left navigation and go to "Official Macintosh/OS X Update Client". Download this and install it. Follow the instructions on the article I have mentioned above.

The update client will automatically map the dynamic IP of the machine to the host name you have selected.

Now you can enjoy working on your machine when you are away from home!!!

Monday, July 17, 2006

Subversion, RadRails, Subclipse and Eclipse

Installed Eclipse 3.2, Subclipse, and Eclipse Plugin for RadRails. You must install the RDT before installing RadRails, So grab this first and then this

Otherwise you will get error message that the dependent library is not found.

The new version of standalone RadRails 0.7 is just out. I think it will be available for download anytime.

I don't know how to get rid of the missing JavaHL library in standalone RadRails. This prevented me from configuring the Subversion. This problem is happening in the other configuration also.

Got some help from Rails mailing list. Select the JavaSVN (Pure Java) as the SVN interface. The error message disappeared.

Thursday, June 01, 2006

Upgrading old rails application for new rails version

Run the following command from your application directory:

rake rails:update

This will update all the configs, scripts and javascripts to the latest

Sunday, February 19, 2006

JSP 2.0, MySQL Server and Tomcat 5.5

Installed JDK 1.5 by making it the first entry in the path variable. Oracle was pointing to JRE 1.3.
Installed Tomcat 5.5. This version runs as a windows service and does not have the usual start and stop tomcat features. Wonder why.
Installed the MySQL server. Created an admin account with admin as the password. My SQL server runs on port# 3306. During the creation of the account it failed to connect to the MySQL server because windows was blocking the port.
To allow the connection to the MySQL server port go to control panel -> firewall -> advanced and new configuration. Name the description of service as MySQL server and provide the name of your computer (or just say localhost, windows automatically changes it to the name of your computer). Enable the TCP/IP by giving the external port number as 10061 and internal port number as 3306. Save it. Now the configuration assistant will complete with no problem when you click on the "Retry" button.

Created a test table by following the Data Source configuration instructions for Tomcat 5.5. You have include a Context entry in the server.xml with data source configuration settings. You must also create a web.xml file. Deploy the test.jsp as war file. You will be able to run it and see the output of the JSTL tags which queries the table and shows the data in the table.

If you get exception related to JSTL tags then you must copy the JSTL tag related libraries to your WEB-INF/lib directory.

The new features of JSP and JSTL allows rapid development of dynamic web pages driven by database. This is a perfect solution for web apps that are just reporting tools with no business logic. In this case the application is simple and does not need a domain model, intergration tier etc.

JSF on Mac OS X

1) Installed the open source JSF plug-in for Eclipse.
2) Installed Tomcat and Sysdeo plug-in.

I was able to run simple login app using JSF. It is very easy to use the JSF XML editor. It gives context help. Defining the navigation is also very easy by using the Palette feature of plug-in. This lends itself for visual development. It generates all the XML code for navigation rules etc.

Also looked at using WSAD 5.1.2 with its inbuilt JSF capabilities. Decided not to use it. Mainly because it generates a lot of IBM extensions in the generated code. This is not acceptable, since portability is very important. Clients who want to use open-source tools must be able to run my apps.