Wednesday, November 25, 2009

Detect Firebug using javascript

Firefox users with FIREBUG add on, would have often seen messages stating "Firebug is known to make Google Mail slow unless it is configured correctly".

Firebug detection can be implemented using javascript

 


Windows.console.firebug will return the version of firebug.

Sunday, August 9, 2009

Production log analyzer - RAWK

Performance tuning and code optimization are vital for any application.

The hardest thing to do is to identify the parts of application that are sluggish. Once identified - they need to be optimized with care (be careful not to break present business logic in the process of optimization...... This is were test cases comes for rescue)

One of the simplest but powerful tool that I came across is ( REFERENCE )

Installation : None......... There is no installation, you just have to copy the RAWK.rb file ( SOURCE) and pass the log file you want to process.

Usage : ruby rawk.rb < production.log

This will list out the entire report, detailing the request action, MIN & MAX rendering times etc.

Most importantly RAWK is very fast.

Saturday, June 27, 2009

Rails 2.x substantials

>> New template naming syntax.
action.type.renderer
.rhtml > .html.erb
.rjs > .js.rjs
.rxml > .xml.builder
.haml > .html.haml

>> Sexy Migrations

>> rake routes
Lists all routes defined for your application

>> rake db:migrate:reset
This will drop the database and will create the database.

>> rake db:migrate:redo
rollback one migration and migrate back up. If you need to go further than one step back pass the STEP=x parameter (rake db:migrate:redo STEP=X)

>> Connection Pooling

>> Deprecations
• find(:all) not find_all
• form_for not form_tag
• pagination is gone

>> Active Record validation :allow_blank
 
validates_length_of :name, :maximum => 15, :allow_blank => true
user = User.new(:name => "")
user.valid? #=> true

>> Commercial DB's out of rails core, available as gems
 
gem install activerecord-oracle-adapter
gem install activerecord-sqlserver-adapter
gem install activerecord-firebird-adapter
gem install activerecord-frontbase-adapter
gem install activerecord-openbase-adapter
gem install activerecord-sybase-adapter

>> Partials can have their own layouts
 
<%= render :partial => 'user_info', :layout => 'boxed', :locals => {:user => @user} %>

>> Accessing helper
 
class ApplicationController < ActionController::Base
# Our many helpers that need to be available throughout the app
[:formatting, :highlighting, :i18n].each { |h| helper h } ...
end

class ApplicationController < ActionController::Base
# Make all helpers in app/helpers/**/ available
helper :all ...
end

>> Cookie based session are the new Default session store
Previously it was file based session store

Wednesday, April 8, 2009

GIT Warning: LF will be replaced by CRLF

I am using msysgit on windows 2000

After setting up the repository and when I tried to add files to GIT index (inorder to have my files considered for next commit) ........ I got

Warning: LF will be replaced by CRLF in FILENAME

After googling I found this a default GIT setting and can be overridden by issuing

git config core.autocrlf false

in Bash mode


A note on LF & CRLF

Most Unix operating systems represent the end of each line with a line feed (LF) character. However, the Windows operating system represent the end of line with both a carriage return (CR) and a LF.

Monday, April 6, 2009

Git on windows - Basics

GIT has now become the preferred source code management tool for Rails community. GIT is at its best when used in Linux / Mac platforms, here we will see how this can be used in Windows. GIT still has few issues in windows but the basic functionalities should work fine.

GIT for windows can be downloaded from Google

There some good links detailing the installation steps

> Using SSH

> Using PuTTY

Follow the above links to finish installation.

Once done with this we are ready to start using GIT as SCM tool.

Getting started - To start GIT bash Right click on your project directory and select 'Git Bash Here' ( if you are a fan of typing commands or else use GUI option)

This will open a CMD window, start by typing 'git help'

Create Git repository - to create a git repo. for your project type - git init

I don't want to reinvent the wheel, so just providing a list of useful links which has very good articles on GIT usage.

Useful links

> Github
> User guide
> GIT commands
> Access issue

Sunday, April 5, 2009

Nice output for Ruby objects

Ruby has a wide range of methods to format the output of an object.

Like

1) Inspect
2) y or to_yaml
3) PrettyPrint

y is actually used as a shorthand for to_yaml

example
 
a={'1'=>'one','2'=>'two','3'=>'three','4'=>'four'}

y a

puts a.to_yaml

generates the same output.

Below are the ouputs using different output methods

> Using normal puts
 
usage: puts a

output:

1one2two3three4four

Using y or to_yaml

usage: y a or puts a.to_yaml

output:

"1": one
"2": two
"3": three
"4": four

> Using PrettyPrint

usage: Please do a require 'pp' in your script file,
 
pp a

output:

{"1"=>"one", "2"=>"two", "3"=>"three", "4"=>"four"}

> Using inspect
 
usage: puts a.inspect

output:

{"1"=>"one", "2"=>"two", "3"=>"three", "4"=>"four"}

Thursday, April 2, 2009

Ruby - DUP vs CLONE

Both DUP & CLONE can be used to create shallow copy of an object. Both copies the instance variables of obj. But we need to be selective in their usage.

Few difference between these are

1) CLONE copies both FROZEN and TAINTED state of an object, where as DUP only copies TAINTED state of an object.

2) With CLONE you can copy any singleton methods of an object but DUP does not support this.

CLONE is used to duplicate an object, including its internal state, DUP typically uses the class of the descendent object to create the new instance.

I had some bitter experience while using DUP for duplicating an ActiveRecord row, this ended up in losing the original one the same worked fine with CLONE.


A good article on Objects states can be found here


Frozen state:

The object can not be modified any more.

Example
 
a = [ "a", "b", "c" ]
a.freeze
a << "z"

Will return

`<<': can't modify frozen array

Friday, March 27, 2009

Duplicating Activerecord record

Was trying to copy an existing DB record by using
 
parent_record = User.find(1)

new_user = User.new(parent_record)

new_user.name = 'new_name'

new_user.save

But this ended in throwing stringify_keys error for User

This can done by specifying

 
new_user = User.new(parent_record.attributes)


Hope this helps!

Wednesday, March 25, 2009

Binary conversion in Ruby

We hardly stretch ourselves to limit unless situation demands to do so.

My requirement - convert a decimal to binary conversion

My first impression - there would be a to_b default method available in ruby which I can use straight away. But it was not so.

But as always it is quite simple to do it in ruby,

number.to_s(2)

gives the binary equivalent of the number

try this from ur IRB

3.to_s(2)

similarly for any base conversion just pass the base value to to_s

Example

3.to_s(10) for base 10 conversion.

Monday, March 16, 2009

Database log file size issue

Recently I faced a problem where my SQLServer 2005 ran out of space for log files. Usually the log files can be reduced by shrinking them but this time the transaction logs were so much huge that I was not even allowed to run shrink log command.

My DB was in Recovery phase.

My friend Dagupati ( a professional DBA ) helped me getting out of this trouble.

Following are the steps to be followed in sequence to achieve this.

1) Take the DB into emergency mode.

ALTER DATABASE yourDBname SET EMERGENCY
2) Bring DB to single user mode.

ALTER DATABASE yourDBname SET SINGLE_USER

3)Repair you DB

DBCC CheckDB ('yourDBname', REPAIR_REBUILD)

if the above command fails, try this

DBCC CheckDB ('yourDBname', REPAIR_ALLOW_DATA_LOSS)

NOTE : This may result in dataloss

4) Bring you DB to multi user mode

ALTER DATABASE yourDBname SET MULTI_USER

By now you should have your DB up & running.

DB at times enter into SUSPECT mode - restarting server should solve them if not follow the above steps.

To be on safer side take full / transactional backups regularly

Handel database NULL values in rails

I was in the impression that rails takes care of

1) nil to NULL when inserting, and

2) NULL to nil while fetching records through Active record

But this proved wrong when my application running in SQL server 2005 fails to detect database NULL fetched from DB.

The fetched value was not even caught by blank? method.

Found this article while googling on this issue, this more or less matched the problem I was facing.

I tried it and was successful.

I am providing a snapshot of the article
 
ActiveRecord::Base.class_eval do
def attributes_from_column_definition_with_null_fix
returning attributes = attributes_from_column_definition_without_null_fix do
attributes.each_value { |value| value.replace('') if value == 'NULL' }
end
end

alias_method_chain :attributes_from_column_definition, :null_fix
end

This helped me in dealing with DB NULL values. Certainly without this article it would have been a tough going to find a way around for this issue ;).

Have also made a thread for this in WorkingWithRails, just to make sure the fix is valid and to get expert comments on the fix.

Sunday, March 15, 2009

Calling RAKE tasks

The syntax for calling a Rake task within rails env,

Rake::Task[TASK_NAME].invoke

If you need to call a rake task from a standalone ruby script, then do remember to include 'rake' files.

Bellow I have provided an usage on how to call a RAKE task from a rufus scheduler script.

My scheduler script is placed inside /lib folder

Also the script will fail to locate your rake task if just call a RAKE method without loading the RAKE file ( the .rake file in which you have your tasks defined ).

So, make sure you load your rake task files.

USAGE
 
require 'rubygems'
require 'rake'
require 'rufus/scheduler'

load File.join( RAILS_ROOT, 'lib',
'tasks', 'my_task.rake')


scheduler = Rufus::Scheduler.start_new

scheduler.cron("0 17 * * 0") do
Rake::Task["maintenance:delete_order_files"].invoke
end

This when triggered will call 'delete_order_files' task defined in a .rake file called MY_TASK.RAKE having namespace 'MAINTENANCE'

Monday, March 9, 2009

Schedule using Rufus scheduler

We learned how to create Rake tasks in rails app. Next thing in process will be scheduling these tasks.

I opted for Rufu-Scheduler, mainly bcs it is quite simple to implement/configure

You can download the gem directly from : http://gems.rubyforge.vm.bytemark.co.uk/gems/

There some good resources in net which describes usage of Rufus scheduler.

Like :http://rufus.rubyforge.org/rufus-scheduler/

But some how I got myself into trouble in getting this to working ;(

Following are questions that bubbled in my mind while implementing Rufus.

>> Where do I put the scheduler code?

>> How will rails trigger my tasks, do I need to include something in my config. file?


I created a file in my /lib dir named myscheduler.rb, this contains the scheduler code and inorder to allow rails to load your rufus scheduler, you have to do

require ' myscheduler'

in environment.rb


My myscheduler.rb has

  
require 'rubygems'
require 'rake'
require 'rufus/scheduler'
load File.join( RAILS_ROOT, 'lib',
'tasks', 'mytasks.rake')

# Note include file containing your rake tasks
# Else you will get - Don’t know how to build
#task XXXXX’ error for the tasks you
#have defined

scheduler = Rufus::Scheduler.start_new

scheduler.every("1m") do
puts "Scheduler invoked"
end

restart the server and check for 'Scheduler invoked' in your CMD.

Got it ......... your half done with your scheduling, take a break ;)

Wednesday, February 18, 2009

Raking in rails

Rake tasks are one of the most power but still under utilized part in rails.

Building rake tasks makes in much easier for manual execution of scripts and plays a big role when scheduling a job.

We might have taken the command 'rake db:migrate' lightly, but it is the time to explore the components behind this.

'Rake --tasks ' lists the available tasks that can be performed by rake

We can create our now Rake tasks by creating .rake files in side lib/tasks dir in rails app.

Introducing NAMESPACE and TASK

TASK : This block defines what actually you want your ruby code to perform.
 
task :my_first_rake_task do

puts "This is my first rake code"

end

save this sample code in lib/tasks with any name ( with rake ext. )

Now, in cmd run 'rake my_first_rake_task'

...... existed!?? theres still more......

NAMESPACE

To manage your tasks in a better/ logical way you can bind them to a NAMESPACE

USAGE
 
namespace :test do
task :my_first_rake_task do

puts "This is my first rake code"

end
end


in CMD run rake test:my_first_rake_task

Description

Now that you have learned how to create a rake task, Next question is ........ how to give description for the task you have created????

simple...

use desc
 
namespace :test do
desc "This is a simple example to show the usage of rake tasks in rails"
task :my_first_rake_task do

puts "This is my first rake code"

end
end

In CMD type RAKE --tasks

one of the entry in the list will be

rake test:my_first_rake_task #This is a simple example to show the usage of rake tasks in rails

Wednesday, January 28, 2009

Ungenerate Stuffs in rails

Rails 'generators' makes it quite easy to create basic model, controller, helper & test skeleton files

But lately I found that it is equally easy to clear files created by generator by using DESTROY.

Example

ruby script/destroy controller XXXX

Will remove all files dumped by rails for command ruby script/generate controller XXXX

ruby script/destroy scaffold XXXX

Will remove all files dumped by rails for command ruby script/generate scaffold XXXX