Wednesday, March 21, 2007

How to use migration

Yavor Ivanov over at rubycorner.net started a mini series on Rails migration. So far there is one article and I already learned a few things that I didn't know.

How to use Rails Migrations - Part I

I created a table with :created_at column as :null => false but I didn't define the default value so I was having problem with specifying the datetime in my test fixture.

I solved that problem by putting this in my test fixture:
created_at: <%= DateTime.now.strftime('%y-%m-%d %H:%M:%S') %>
What I really should have done is created the column like this.
t.column :created_at, :datetime, :default => Time.now

Tuesday, March 20, 2007

Ruby on Rails Caching

Gregg Pollack over at Rails Envy posted two articles on Ruby on Rails Caching. If you have performance issue, you might want to check them out.

Ruby on Rails Caching Tutorial - Part 1

Ruby on Rails Caching Tutorial - Part 2

Monday, March 19, 2007

Ruby on Rails screencasts

I found this website, Railscasts, that has free Ruby on Rails screencasts. So far, there are 7 screencasts and they are posted pretty regularly.

Friday, March 16, 2007

Acts As State Machine plugin

I just finished reading Bruce Tate article, Crossing borders: Extensions in Rails (The anatomy of an acts_as plug-in), where he mentioned the acts_as_state_machine plugin for Rails. If you ever have model with known transition paths between different states then this plugin will be a great help to you.

Here is an article, The Complete Guide to Rails Plugins: Part 1, on Nuby on Rails showing how to install and create Rails plugin.

And finally, you can go to the acts_as_state_machine plugin's author blog, Acts As State Machine, to see where to download and how to use the plugin.

Here is my example of how to use the plugin to keep track of a light fixture with three state (off, low, and high).

# The Migration class for light
class CreateLights < ActiveRecord::Migration
def self.up
create_table :lights do |t|
t.column :name, :string
t.column :status, :string
end
end

def self.down
drop_table :lights
end
end

# The Model for light

# A simple transition for a light with three states, (off, low, high)
#
# +---------+ switch +---------+ switch +---------+
# | off |-------->| low |-------->| high |
# +---------+ +---------+ +---------+
# ^ |
# |_________________________________________|
#
class Light < ActiveRecord::Base
acts_as_state_machine :initial => :off, :column => 'status'

state :off
state :low
state :high

event :switch do
transitions :from => :off, :to => :low
transitions :from => :low, :to => :high
transitions :from => :high, :to => :off
end
end

-------------------------
Here is a sample run:

>> l = Light.create
=> ...
>> l.current_state
=> :off
>> l.switch!
=> nil
>> l.current_state
=> :low
>> l.switch!
=> nil
>> l.current_state
=> :high
>> l.switch!
=> nil
>> l.current_state
=> :off

Thursday, March 15, 2007

Tips for working with Test Fixtures in Rails

I have a requirement in my migration script that created_at column can not be null.

t.column :created_at, :datetime, :null => false

This cause the Test Fixtures loading to fail. My first attempt to remedy this problem was like this.

created_at: <%= DateTime.now %>

This did not work since the date time format is incorrect. The correct format is year-month-day hour:minute:second.

So, I changed it to

created_at: <%= DateTime.now.strftime('%y-%m-%d %H:%M:%S') %>

and it works.

I don't know if there is a better way to do this but this works for me. Since I went around looking for the solution, I decided to write it down.

Wednesday, March 14, 2007

Validate a number is an integer and within a certain range

Use validates_numericality_of , and validates_inclusion_of to check that a number is an integer and within a certain range.

For example:

You only want to allow people to enter a number between 21 and 30. Here is how you would do it.

validates_numericality_of :n, :only_integer => true, :message => "can only be whole number."
validates_inclusion_of :n, :in => 21..30, :message => "can only be between 21 and 30."

Tuesday, March 13, 2007

Ruby on Rails Quick Reference

I was looking for a way to update my rails application to rails 1.2.3 when I found this guide, Ruby on Rails Quick Reference. It has descriptions to many frequently use rails features.

rake rails:update is how you update your rails application.

Found a cheat sheet with a great deal of information:

Ruby on Rails 1.1 Reference

Drop Derby and goes back to MySql

After my rant yesterday about Derby not supporting column rename, I checked ActiveRecord-JDBC document for Derby and column_rename is not one of the supported feature.

Here is the list of databases and the level of support taken from the document.
  • MySQL - Complete support
  • PostgreSQL - Complete support
  • Oracle - Complete support
  • Microsoft SQL Server - Complete support except for change_column_default
  • DB2 - Complete, except for the migrations:
    • change_column
    • change_column_default
    • remove_column
    • rename_column
    • add_index
    • remove_index
    • rename_table
  • FireBird - Complete, except for change_column_default and rename_column
  • Derby - Complete, except for:
    • change_column
    • change_column_default
    • remove_column
    • rename_column
  • HSQLDB - Complete
Since MySql is completely supported, I switch to using MySql as the database back end for development.

I did notice one little problem with Netbeans today. The "Generate" menu item disappeared from the menu for some reason. I closed and reopened Netbeans but that didn't do anything. Finally, I closed the project, reopen it and the Generate menu item came back. It only happened once. I don't remember what I did to cause the problem though.

Monday, March 12, 2007

Derby does not support renaming column

-- rename_column(:users, :username, :user_name)
rake aborted!
rename_column is not implemented

Opps, I hit another snag when trying to rename username to user_name. Apparently, Derby does not allow renaming of column. I wiped out the database and started over but that is not a practical way to do thing going forward. I think my experiment with Derby is coming in an end here. I wonder why Sun is endorsing a database that is missing such fundamental feature. I don't remember using a database that does not support renaming of column. I guess there is a first for everything.

Now, I regretted that I read, "If You Thought Rails Development Was Fast Before...". I wouldn't have tried Derby without reading that article. It should be renamed to "If You Thought Rails Development Was Fast Before... Here Is How To Slow Yourself Down". I know it is a cheap shot but that article really make me think that I would be more productive using Derby as my development database.

Sunday, March 11, 2007

Using Rails migration with Netbeans 6.0 M7

I hit a temporary road block while following the steps from this article, If You Thought Rails Development Was Fast Before.... I wanted to use migration instead of sql to create the table in the database. After using the generator to create the migration file, I couldn't figure out how to call the db:migrate task in rake. There is no obvious way to call it from Netbeans 6 itself. I look everywhere but I couldn't find anything. I look in jruby-0.9.2 directory and rake is there but there is no bat file to call it. So, I created a bat file to call rake then execute rake db:migrate directly from the command prompt. That did the trick.

Here is the link to a Derby tutorial on how to create a new database in Derby from Netbeans.

Derby Tutorial

Thursday, March 08, 2007

OpenID and Rails

Ruby Inside has a collection of links to discusses and resources on OpenID and Rails. At the bottom, there is a link to Bernie Thompson's screencast and additional OpenId resources.

OpenID for Rails - Bernie Thompson

8 OpenID Resources for Rails Developers - Ruby Inside

Wednesday, March 07, 2007

Rails' validators

Every wonder how to use all those validators (validates_presence_of, validates_uniqueness_of, validates_size_of, validates_acceptance_of, etc..), in Rails? Head over to Juixe TechKnow and read Rails Model Validators. The author has simple samples and explanations for those and a few more.

Monday, March 05, 2007

Screencast of Ruby editing features in Netbeans 6

Roman Strobl, famous for creating screencasts of Matisse GUI Builder in Netbeans 5.0, is at it again. This time he created two screencasts to demonstrate Ruby and Ruby on Rails features in Netbeans 6.

Two Demos: JRuby on Rails and Advanced Ruby Editing in NetBeans

Sunday, March 04, 2007

Ruby Block

If you use Ruby for any thing more than a simple "hello world" program then you probably hit Ruby block and closure. I write a lot of Ruby code to process data files. This is an ideal way to open a text file and process all lines within it.

File.open("filename", "r") do |file|
file.each_line do |line|
# do something with the line
end
end

It automatically close the file when it reached the end of the file.

If you want to learn more about Ruby block then head over to Darwinweb and read Ruby Blocks as Closure.

Friday, March 02, 2007

Great tips for .Net developers moving over to Ruby

Over at Softies on Rails, Jeff Cohen has a great on going series of articles titled, Ruby on Rails for .Net developers. The latest one is on map and collection. I find them quite interesting and helpful. In his example, he has C# codes and the equivalent Ruby codes for us to have a frame of reference when learning to write code in the Ruby way.

I am a .Net developer by day and a Ruby adventurer by night. Although, I am trying to use more and more Ruby code in my day job. I am currently using Ruby for all my scripting needs. Before Ruby, I was using Perl and that was an adventure.

Anyway, if you are a .Net developer and wondering what Ruby is all about then you definitely should check out Softies on Rails.

Netbeans 6 and auto completion

I started to use Netbeans for all my ruby programming tasks and the auto completion is wonderful. Before, I had to search around Ruby Doc for various libraries and methods but now I can just type the class name and press ctrl-space to get all the methods info. I do find one problem with the auto completion though. When I am editing a single file and not a ruby project, I don't get any auto completion help beside the basic variables within the file. I do get the syntax highlighting though. Unfortunately, a lot of my ruby scripts are quick and dirty and do not warrant creating a whole project just to write it. Maybe there is a way to activate the auto completion in single file editing mode. Anyway, beside that little problem, everything is working great so far.

Thursday, March 01, 2007

Articles about Rails Performance on the web

This blog entry, Rails Performance Link Fest, from Juixe TechKnow has a ton of links to various web resources regarding Rail Performances.

NetBeans IDE 6.0 M7

My eternal search for a Ruby editor led me to NetBeans IDE 6.0 M7. It is still in the earlier stage of development but I find its Ruby supports to be pretty good. It has code completion and syntax highlighting. The code completion part is what I like about it. I can't live without code completion.

You can get milestone 7 by going to http://www.netbeans.info/downloads/dev.php and select Q-Build for Build Type. Then download NetBeans IDE 6.0 m7 build 200702191730.

Here is a series of screenshot from Tor Norbye's Weblog

Ruby Screenshot of the Week
Ruby Screenshot of the Week #2
Ruby Screenshot of the Week #3
Ruby Screenshot of the Week #4
Ruby Screenshot of the Week #5