Posts Tagged: ruby

Rails Refactoring tip: Dry up your constants

 by Anand  on   04 Aug 2011

If you observe your rails app, you might come across some set of values constantly being used. It is a good idea to identify them and dry them up. For example, in the models, you might have used a Regular expression for checking the validity of email attribute.

in app/models/account.rb

 validates_format_of :email,:with => /(^([^,@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i 

in app/models/delegate.rb

validates_format_of :email,:with => /(^([^,@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i

Don’t you see, its very hard to keep using it across models or any other ruby files. For this, We can create a file called constants.rb in config/initializers and declare a constant (with a good, rememberable name) there.

In config/initializers/constants.rb

EMAIL_REGEXP = /(^([^,@\s]+)@((?:[-_a-z0-9]+\.)+[a-z]{2,})$)|(^$)/i

Restart the server now. Then in the model file shown above, we can use it like

validates_format_of :email,:with => EMAIL_REGEXP

We can use the same technique with other constant values that are used more than once in the application.

Equality Gotcha of ActiveRecord Objects

 by Anand  on   22 Jul 2011

Two Activerecord objects when compared over == operator returns true when they are instances of the same ‘model class’ && if they have same ‘id’ values. This operation is not an attribute-by-attribute comparison. Beware, this behavior can give problems when you do a lot of == operations b/w Activerecord objects, in your application, in which case you need to override == operator of ActiveRecord::Base according to your needs.

Here is a sample behavior of == operator.

ruby-1.9.2-p180 :001 > p1 = Person.first
=> #<Person id: 1, name: “John”, email: “”>
ruby-1.9.2-p180 :002 > p2 = Person.first
=> #<Person id: 1, name: “John”, email: “”>
ruby-1.9.2-p180 :003 > = “somethingelse”
=> “somethingelse”
ruby-1.9.2-p180 :004 >
=> true
ruby-1.9.2-p180 :005 > p1
=> #<Person id: 1, name: “somethingelse”, email: “”>
ruby-1.9.2-p180 :006 > p2
=> #<Person id: 1, name: “John”, email: “”>
ruby-1.9.2-p180 :007 > p1 == p2
=> true

ActiveRecord finders behave differently for various types of finders. Suppose you have a model called Account. Here are the ways you can get a record with id 34 in the `accounts` table.

acc = Account.find(34)
acc = Account.where(:id => 34).first
acc = Account.where(:id => 34)

Suppose a record with id = 34 does not exist in `accounts` table. Most programmers would think that the finders will throw ActiveRecord::RecordNotFound exception in all cases. No, thats not the behavior here. In the first case, using ‘find’ method returns ActiveRecord::RecordNotFound exception. Where as in the second case using ‘where’ method, it returns nil object. In the third case it returns an empty array []

ruby-1.9.2-p180 :001 > Account.find(34)
ActiveRecord::RecordNotFound: Couldn’t find Account with ID=34
ruby-1.9.2-p180 :002 > Account.where(:id => 34).first
=> nil
ruby-1.9.2-p180 :003 > Account.where(:id => 34)
=> []

If we find records using ‘find’ method, it is assumed that we have prior knowledge of the table ‘accounts’ and the primary key values. So, if there is no record with that id, an exception is thrown. If we use ‘where’ method to find records, we are querying based on some conditions. If the query finds anything that matches our conditions, it returns the result. If it cannot find any record that matches our conditions, it returns an empty array or nil object.

Empty array is returned when we fire a non-singular query (as in third case). A Nil object is returned if we fire a singular query. This behavior have to be kept in mind when find records and apply conditions on them, in the Rails controllers.

Rails Performance Tip: Query Optimization

 by Anand  on   11 Jul 2011

Rails applications will get significant performance boost if the sql queries sent to the database are optimized. Database cialis super active must not be hit with requests unless there is an absolute necessity.

Two Basic online writing sites steps for Optimization:

  1. Add database indexes on all foreign keys
  2. add_index :tasks, :project_id
  3. Use Eager loading to avoid n+1 query problems, in sensible places.
  4. Project.find(12).includes(:tasks, :notes)

    QueryReviewer gem:

This gem helps a lot in optimizing the SQL queries.

For every page request, it gives good statistics on the number of queries, number of slow queries, in-efficient queries etc.,
Check it out.

Image handling in RoR API using Paperclip

 by Nisha  on   13 Aug 2010

Image handling is a common task in an application and for Ruby on Rails we have quite a few plugins like rmagick, minimagick, paperclip, attachment-fu etc available to effectively do the same. Paperclip is by far the most loved and popular plugin used to attach images to a model in a rails application. It makes life easy with good documentation and screencasts available to guide through. But at an advanced level, the challenge comes in when an api interface to upload and download images needs to be provided for the model. As paperclip does not support this by iteself, and there is not much help or guide available to help solve this problem, this post makes life easier for ROR api developers, who have to provide a way to attach images sent through xml to the model.

Continue reading →