Friday, April 24, 2009

Use Migration Helpers to ease your migration script

One of the purpose of rails migration script was to wrap SQL with simple ruby code. But still we need some SQL for creating foreign key or inserting some default data or updating some existing data. There is a rails plugin to solve this problem.migration_helpers provides some basic helpers for writing migration scripts.

It wraps

  1. Add/remove foreign key
  2. Insert statements
  3. update statements

Here is a sample migration that uses insert and update statement.

class CreatePosts < ActiveRecord::Migration
    def self.up
      create_table :posts do |t|
        t.string :title
        t.text :body
        t.boolean :published
    
        t.timestamps
      end
    
      insert_row('posts', :title => 'Dummy Title', :body => 'A sample post', :published => false)
      update_row('posts', :set => { :published => true }, :where => { :title => 'Dummy Title' })
    end
    
    def self.down
      drop_table :posts
    end
end
And here is a sample migration that uses foreign key reference.
class CreateComments < ActiveRecord::Migration<br />    def self.up<br />      create_table :comments do |t|<br />        t.text :body<br />        t.boolean :published<br />        t.references :post<br />    <br />        t.timestamps<br />      end<br />    <br />      add_foreign_key('comments', 'post_id', 'posts')<br />    end<br />    <br />    def self.down<br />      remove_foreign_key('comments', 'posts')<br />      drop_table :comments<br />    end<br />end

Caution:

This is really a nice plugin but I needed to modify some code to work remove_foreign_key.

In plugins/migration_helpers/lib/migration_helpers_tasks.rb file replace the remove_foreign_key with the following code

def remove_foreign_key(table, target_table, constraint_name="#{table.to_s}_#{target_table.to_s}_fkey")<br />    execute "ALTER TABLE #{table.to_s} DROP FOREIGN KEY #{constraint_name};"<br />    execute "ALTER TABLE #{table.to_s} DROP KEY #{constraint_name};"<br />end
Reference:

http://github.com/patientslikeme/migration_helpers/tree/master



Thursday, April 23, 2009

Transaction in rails 2.3.2

In rails when we want some series of tasks to be atomic we use transaction. But how should we write our code to support transaction?

Let me explain how transaction in rails works. If any code inside a transaction raises an exception

  1. the transaction block rescues it
  2. rolls back the database and
  3. re throws the exception

So we need to make sure that statements that are not complete, raise exception. Here are some scenarios with explanation.

For all the scenarios the Comment model is like,

class Comment < ActiveRecord::Base
  belongs_to :post
  validates_presence_of :body
end

As model.collection << child_model does not raises exception the post is saved, as the transaction is unaware of the data save failure.

test 'transaction should not rollback transaction with collection create method' do<br />  is_comment_saved = false<br />  Post.transaction do<br />    post = Post.new({:title=> 'Test title', :body => 'A sample post', :published => true})<br />    post.save!<br />    is_comment_saved = post.comments << Comment.new({:published => true})<br />    #Comment with out body should be not saved for validation<br />    #but this does not raise exception so the transaction is not rolled back<br />    #I know that rails convention is that you first assign the comment and then save post<br />    #But there might be situation when you might want to save model which is unrelated to post in the same transaction<br />  end<br /><br />  assert_equal(1, Post.count)<br />  assert_equal(0, Comment.count)<br />  assert_equal(false, is_comment_saved)<br />end

To support transaction we need to write some thing like this,

test 'transaction should rollback transaction with throwing exception manually' do<br />  is_comment_saved = false<br />  begin<br />    Post.transaction do<br />      post = Post.new({:title=> 'Test title', :body => 'A sample post', :published => true})<br />      post.save!<br />      #Comment with out body should be not saved for validation<br />      raise Exception unless post.comments << Comment.new({:published => true})<br />    end<br />  rescue Exception<br />  end<br /><br />  assert_equal(0, Post.count)<br />  assert_equal(0, Comment.count)<br />  assert_equal(false, is_comment_saved)<br />end

model.collection << returns false the operation fails. So raising an exception while it returns false causes the transaction to rollback.

Let me give you a scenario with nested transaction.

test 'default Nested transaction should rollback with raising Exception' do<br />  begin<br />    Post.transaction do<br />      post = Post.new({:title=> 'Test title', :body => 'A sample post', :published => true})<br />      post.save!<br />      Comment.transaction(:requires_new => true) do<br />        post.comments.create({:body => 'A sample comment', :published => true})<br />        raise Exception<br />      end<br />    end<br />  rescue Exception => error<br />  end<br /><br />  assert_equal(0, Post.count)<br />  assert_equal(0, Comment.count)<br />end

Note: For nested transaction in rails 2.3.2 by default any transaction inherits the transaction of it’s parent transaction. To make a new child transaction you need to pass “:requires_new => true” as the parameter of transaction method.

Identical to single transaction nested transaction behaves same if you throw an exception. So if you really mean to use a child transaction, you will need to handle exception inside or around the child transaction.

The above example behaves same even if we do not use “:requires_new => true” for child transaction. now If you want to break the child transaction and not to interfere the parent transaction, you can use “ActiveRecord::Rollback”.

Transaction relays all the exception except ActiveRecord::Rollback. If you raise ActiveRecord::Rollback then the steps are

  1. the transaction block rescues it
  2. rolls back the database and
  3. DOES NOT re throw the exception

Here is an example,

test 'nested transaction should not rollback parent transaction that throws ActiveRecord Rollback in child transaction' do<br />  begin<br />    Post.transaction do<br />      post = Post.new({:title=> 'Test title', :body => 'A sample post', :published => true})<br />      post.save!<br />      Comment.transaction(:requires_new => true) do<br />        comment = Comment.new({:body => 'Test', :published => true, :post_id => post.id})<br />        comment.save!<br />        raise ActiveRecord::Rollback<br />      end<br />    end<br />  rescue Exception<br />  end<br />  assert_equal(1, Post.count)<br />  assert_equal(0, Comment.count)<br />end

In rails 2.3.2 ActiveRecord::Rollback does not work for child transaction that is not defined as :requires_new => true.

Here is another scenario for that test,

test 'default nested transaction should not rollback even child trasnsaction that throws exception in child transaction' do<br />  Post.transaction do<br />    post = Post.new({:title=> 'Test title', :body => 'A sample post', :published => true})<br />    post.save!<br />    Comment.transaction do<br />      comment = Comment.new({:body => 'Test', :published => true, :post_id => post.id})<br />      comment.save!<br />      raise ActiveRecord::Rollback<br />    end<br />  end<br />  assert_equal(1, Post.count)<br />  #Here comment is saved too<br />  assert_equal(1, Comment.count)<br />end

As you can see raising ActiveRecord::Rollback does not impact the result.

These are some of the scenario explained, which should help you to choose appropriate way to use transaction for your application.

You can download the test project from here.



Add custom rake task in your rails project

It is very easy to create a custom rake task in rails. We can often use this feature to ease our daily work. Recently I needed to run a cron job for a rails project, which is the perfect place for a custom rake task. You can follow these process to create a task.

1. Create a rake file as your_tasks.rake and put it in project_path\lib\tasks\

rails detects task from project_path\lib\tasks\

2. A sample rake task

task :start do
  #do some magic and start the cron
end
task :stop do
  #do some more magic and stop IT
end

3. Now run in command prompt from the project folder as

rake start

To make your tasks more meaningful you might want to try giving namespaces and a little description which explains the task a bit.

Here the simple modification you need

Rake task

namespace :cron do
  desc "Starts cron job"
  task :start do
    #do some magic and start the cron
  end
  desc "Stops cron job"
  task :stop do
    #do some more magic and stop IT
  end
end

Calling tasks

rake cron:start

Rake gives us the flexibility of defining dependent tasks so that the dependent tasks can be executed first.

Often we may need our rails environment to load before we do any thing. You can do it by

namespace :cron do
  desc "Starts cron job"
  task(:start => :environment)do
    #do some magic and start the cron
  end
  desc "Stops cron job"
  task(:stop => :environment)do
    #do some more magic and stop IT
  end
end

Now when you will run the task, you will find that your environment is now loaded.

Resource:

http://www.railsenvy.com/2007/6/11/ruby-on-rails-rake-tutorial

http://rake.rubyforge.org/

http://martinfowler.com/articles/rake.html

Monday, April 13, 2009

DateTime with zone support in rails fixture

To get time with zone support we usually call, Time.now.utc

But if we use Time.now.utc in fixture like,

fixture1:
deadline: <%= Time.now.utc %>

It gives an error:

ActiveRecord::StatementInvalid: Mysql::Error: Incorrect datetime value: 'Sun Apr 12 11:40:05 UTC 2009' for column 'deadline' at row 1: INSERT INTO job_assignments (job_id, updated_at, id, deadline, transporter_fee, transporter_id, created_at, state) VALUES (245383586, '2009-04-12 09:40:07', 809788707, 'Sun Apr 12 11:40:05 UTC 2009', 75, 468814034, '2009-04-12 09:40:07', 'assigned')

Because fixtures calls a default to_s function for each fields to create the insert script. Fixtures does not save records through Models. Time.now.utc.to_s generates a string which is not in the format to save date time in mysql. To generate such format we need to call Time.now.utc.to_s(:db). So the fixture turned out like,

fixture1:
deadline: <%= Time.now.utc.to_s(:db) %>

Sunday, February 1, 2009

Png Corner is the solution of rounded/styled corners which is browser compatible

I was searching for an easy and simple implementation of smooth rounded corner that is browser compatible. If you want smooth corners you will need png images and Internet Explorer 6 has issues with png alpha transparency. Then I came with a project pngcorner . This is very easy to use and very small in size(less than 4 kb ). You can download the demo from here.

For png transparency I used unitpngfix , a very small(less than 1 kb ) and yet very effective javascript library. And used a table structure rounded corner template. For detail please visit the project page.

Here is a demo and here is the demo with jquery plugin.

Why use png corners

  1. It is browser compatible(works in IE 6/7, FireFox 3, Opera 9, Chrome 1.x)
  2. It's small(less than 4 kb )
  3. Easy to use(Just follow 3 easy steps)
  4. Can use png transparency feature so that you can create your own styled box.
  5. Same behavior across browsers
  6. Size of your content is totally flexible
  7. You can change images from css
Why special
There are a lot of implementation on rounded corner. And there are simpler implementation.
But if you need smooth(using png images), transparent(that works even in IE6), browser compatible, small(less than 4kb), with flexible content dimension(content can have any dimension) you should use pngcorners.
Places to use
  1. Use to create smooth rounded corner content with shades
  2. Use to create buttons with shades(as the size is expandable you can have small buttons as well as long ones)

Limitations

  1. It uses table for the structure of rounded corner. So your rounded corner is not as flexible as div layout (It is a small sacrifice for IE 6 png transparency)
  2. The images at left, right, top and bottom will be scaled not repeated. As Microsoft.Alpha filter do not support repeating.

Usage

1. Add png _corner. css in page

2. Add html structure for rounded corner, which looks like this,

<table class="rounded_corner" border="0" cellpadding="0" cellspacing="0">
  <tr><td class="top_left"/><td class="top"/><td class="top_right"/> </tr>
  <tr><td class="left"/>
    <td class="content">The content goes here :)</td>
    <td class="right"/>
  </tr>
  <tr><td class="bottom_left"/><td class="bottom"/><td class="bottom_right"/></tr>
</table>

3. Add png hack css in header as shown bellow so that the script is only added for Internet Explorer 6.

4. Add clear. gif in root_file/images

And you should be good to go :)

jQuery Version

There is a jQuery version of png corners. For that you will have to follow all the steps and add another javascript file pngcorners.js. But now the step 2 is now being simplified.

No need to remember all those tags and make your view complex. Just call,

$(".round_me").pngcorner();

Where you are expecting for elements with round_me class name will become rounded corner :)

So it reduces tags and cleans the view a bit.

Caution

When you load you content from ajax call or create your content dynamically after your page is loaded then you have to call the following javascript after you have done loading your content.

pngfix();

I am still searching for a solution with lesser limitation and complexity. So any suggestion is welcome.