Tuesday, July 17, 2007

Help in writing tests in Rails

script/console test

It will load the console in the test environment. Very useful to experiment with the code and write tests.

Saturday, July 14, 2007

Railscookbook example error

NameError in User#list_perms

Showing app/views/user/list_perms.rhtml where line #22 raised:

uninitialized constant UserHelper::Permission

create the permission model without migration.

Also the migration for permissions table does not have a id column. This results in a bug where the update does not work for some cases. So I had to add a primary key column to the permissions table. This fixed the buggy update problem.

How to skip migration in Rails

use --skip-migration switch: Ex: script/generate model user --skip-migration

Thursday, July 05, 2007

How to suppress rendering of layout while generating xml in Rails

def my_xml_method
@foo = Foo.find(:all)
render :layout => false
end

If you have render and respond_to in the same method, you will get the dreaded double render error.

Wednesday, July 04, 2007

How to install RubyInline in Mac OS

$ sudo gem install rubyinline
Successfully installed RubyInline-3.6.3
Installing ri documentation for RubyInline-3.6.3...
Installing RDoc documentation for RubyInline-3.6.3...

Port install did not work:

sudo port install rb-rubyinline
---> Fetching autoconf
---> Attempting to fetch autoconf-2.61.tar.bz2 from http://ftp.gnu.org/gnu/autoconf
---> Verifying checksum(s) for autoconf
---> Extracting autoconf
---> Configuring autoconf
---> Building autoconf with target all
---> Staging autoconf into destroot
---> Installing autoconf 2.61_0
---> Activating autoconf 2.61_0
---> Cleaning autoconf
---> Fetching rb-rubygems
---> Attempting to fetch rubygems-0.9.4.tgz from http://rubyforge.org/frs/download.php/20989/
---> Verifying checksum(s) for rb-rubygems
---> Extracting rb-rubygems
---> Configuring rb-rubygems
Error: Target com.apple.configure returned: configure failure: shell command " cd "/opt/local/var/db/dports/build/_opt_local_var_db_dports_sources_rsync.rsync.darwinports.org_dpupdate_dports_ruby_rb-rubygems/work/rubygems-0.9.4" && /opt/local/bin/ruby -rvendor-specific setup.rb config " returned error 127
Command output: sh: line 1: /opt/local/bin/ruby: No such file or directory

Error: The following dependencies failed to build: rb-hoe rb-rake rb-rubygems rb-rubyforge
Error: Status 1 encountered during processing.

How to use select_tag to create drop down menus in Rails

<%=
select_tag :size, options_for_select(["Small", "Medium", "Large"])
%>

This will create a drop down with the values in the array. You can either declare a constant array in the model and use that like: MyModel::SHIRT_SIZES instead of hard coding it. If it is database driven, write a helper that will return an array of options.

Sunday, July 01, 2007

How to find the helper methods for RESTful nested routes in Rails


1) script/console
2) >> irb ActionController::Routing::Routes
3) rs = ActionController::Routing::Routes
4) rs.named_routes.each {|name, route| puts( name, route) }; 1
5) Just copy the list of helper methods show in the output of step 4 and append path to that name. You must also provide the required ids shown in the output. For example take the output:

user
GET /users/:id/ {:action=>"show", :controller=>"users"}

and in the console, type:

>> user_path 1
=> "/users/1"

The same process can be used for nested routes.

Reference: Rails Routing by David A Black. This book gave me a solid understanding of routes.

Friday, June 29, 2007

Difference between capitalize and humanize in Rails

From the script/console:

>> t = "test"
=> "test"
>> t.capitalize
=> "Test"
>> t.humanize
=> "Test"
>> c = "foo bar"
=> "foo bar"
>> c.humanize
=> "Foo bar"
>> c.capitalize
=> "Foo bar"

How to use hidden field in Rails

<%= f.hidden_field :user_id, :value => current_user.id %>

This passes a hidden variable user_id with the value of current_user.id

Thursday, June 28, 2007

Displaying time only in Rails

Not well documented in the Rails API. Here it is:

<%= f.datetime_select(:time, :discard_day => true, :discard_month => true, :discard_year => true) %>

How to create admin accounts in Rails app

The Memphisto source has rake db:bootstrap task that I use for loading admin users into the database. The dynamic fixture allows using any user and password for a admin account.

Wednesday, June 27, 2007

How to freeze gems using Rake

1. script/plugin install http://svn.ardes.com/rails_plugins/gems
2. rake gems:freeze GEM=gem_name

Monday, June 25, 2007

Migrating Local Subversion Repository to Remote Repository

I have been developing the Rails app on my Powerbook using Subversion with file:/// protocol. So when I had to migrate it to Subversion repository hosted remotely by Rimu I had to do the following:

1) On the laptop:

svnadmin dump ~/home/path/to/svn/repos > some-file-name

2) I used Transmit FTP client to use SFTP to the remote host and copied the some-file-name to the remote machine.

3) Login to the remote machine and run:

svnadmin load subversion-repo-name < some-file-name

I created a new directory on my laptop and did a checkout from remote repository:
svn co --username some_user --password some_password http://www.your-domain.com/project_name/trunk

then svn info shows that the repository is http:// pointing to the remote repository.

svn log http://www.your-domain.com/project_name/trunk

shows all the log messages. Note this did not show all the 10 revisions that I had on my local repository. It showed only the changes that I had made after the migration. So the local repository version was at 10 but the remote repository was moving from version 3.

Debugging Rails App in Realtime with the breakpointer

1) include the line: breakpoint "some description goes here" where you want the program execution to stop.
2) From the rails app root directory run: script/breakpointer
3) Fire the browser and let the app hit the breakpoint, you will be taken to the >> prompt where you can examine variables.

This helped me to customize the Attachment_fu plugin so that image upload is optional.

Saturday, June 23, 2007

Testing XML output in Rails

1. get :action_name, :format => "xml", :id => 1
2. content = @response.body
3. assert_select "title", :text => "Rails Recipes"

The above steps basically simulate http://localhost:3000/xmlcontroller/action_name/1.xml.

Let's say you have multiple records in the xml output you can check:

assert_select "book", :count => 2

In this case there will be two books in xml output.

Thursday, June 21, 2007

.svn: Commit failed

Error:
.svn: Commit failed (details follow):
svn: Out of date: 'vendor/plugins' in transaction '7-1'
svn: Your commit message was left in a temporary file:
svn: '/Users/myprojects/svn-commit.tmp'

svn up first and then svn delete on the files that is no longer required and then commit.

Send Method in Ruby

When you have an object, you can set the values for its attributes by:

obj.send(#{attribute}, value) where attribute is the actual attribute while looping through an array of strings that contains the attribute names. The value is the actual value that is used to initialize the attribute.

Wednesday, June 20, 2007

Recursion in Ruby

Calculate x to the power of y using recursion.

def test(x, y)
if (y == 0)
return 1
else
test(x, y-1) * x
end
end

puts test(2,3)

This was a interesting question during the interview. I never understood recursion. The interviewer skillfully provided some clues for me to figure this one out myself. I wrote down some sample values for x and y in a tabular format. Worked through the problem and surprisingly come up with the right answer!