Tuesday, November 17, 2009

Use of Dirty Objects

Uses of Dirty Objects

Developer have some confusion that how they can get the previous value of the field after update.
So here the rails has a way called Dirty objects.

You can found Module Dirty in rails/activerecord/lib/active_record/dirty.rb
This is just for track unsaved attribute changes.
There are few methods in dirty module as below
* Changed
* Changed?
* Changes
* Included
And it has some constants

DIRTY_SUFFIXES = ['_changed?', '_change', '_will_change!', '_was']

book = Book.find(1)

book.name = 'agiles'
book.changed? # => true
book.name_changed? # => true
book.name_was # => 'rails startup'
book.name_change # => ['rails startup', 'agiles']
book.name = 'agiles with rails'
book.name_change # => ['rails startup', 'agiles with rails']

You can found the details in http://api.rubyonrails.org/classes/ActiveRecord/Dirty.html

Tuesday, June 23, 2009

Remove .svn files / folders

I have found from some where to use the below syntax for remove .svn folders. And it works for me so i thought it might be useful. So i shared this

find ./ -name ".svn" | xargs rm -Rf


find ./ -name “.svn” -exec rm -rf {} \;

Source: http://www.rickhurst.co.uk/category/linux/

Monday, April 20, 2009

Receive Mail with attachment using TMail - Ruby on Rails

Receive Mails using TMail. I like to use TMail for receive mail because TMail is best to handle the header of the email object. There are only a few methods that deal directly with the body of the email. So i just thought to share it. I have used pop3 for receive mail and use TMail for parse it.
For use TMail you need to do install gem.

gem install TMail

def popmail
     require 'net/pop'
     require 'tmail_mail_extension.rb'

     pop = Net::POP3.new 'mail.example.com'
     pop.start 'test-receive@example.com', 'password'

     if pop.mails.empty?
       puts 'No mail.'
       pop.each_mail do |mail|
        email = TMail::Mail.parse(mail.pop)
        subject = email.subject
        from_email = email.from
        body = email.body_html
        if email.has_attachments?
        email.parts.each_with_index do |part, index|
          filename = part_filename(part)
          content_type = part.content_type
          filename ||= "#{index}.#{ext(part)}"
          file = filename
          fname = file.split(".")
          newfilename = fname[0]+'_'+(Time.now.to_i).to_s+'.'+fname[1]
          filepath = "#{RAILS_ROOT}/public/file_attachement/#{newfilename}"
          File.open(filepath,'wb'){|f| f.write(part.body)}
          filesize= File.size(filepath)
       # Do your Logic after getting details

def part_filename(part)
     file_name = (part['content-location'] &&
     part['content-location'].body) ||
     part.sub_header("content-type", "name") ||
     part.sub_header("content-disposition", "filename")

     'image/jpeg' => 'jpg',
     'image/gif' => 'gif',
     'image/png' => 'png',
     'image/tiff' => 'tif'

def ext( mail )
     CTYPE_TO_EXT[mail.content_type] || 'txt'

Note: You can get body part of email by email.body and no need to use of tmail_mail_extension.rb

But it gives your body part two times. one in normal text of body and second is html of the same body. If you want only html of the body then you need tmail_mail_extension.rb. I found that logic of tmail_mail_extension.rb file from somewhere, i forgot the link for that.
But you can write below which i found from somewhere. Write below code in tmail_mail_extention.rb

module TMail
   class Mail

   # returs an String with just the html part of the body
   # or nil if there is not any html part

   def body_html
     result = nil
     if multipart?
       parts.each do |part|
         if part.multipart?
          part.parts.each do |part2|
          result = part2.unquoted_body if part2.content_type =~ /html/i
         elsif !attachment?(part)
          result = part.unquoted_body if part.content_type =~ /html/i
       result = unquoted_body if content_type =~ /html/i

   def parts_observer
     puts "INI"
     puts "content_type: #{content_type}"
     puts "body: #{body}"
     puts "parts.size: #{parts.size}"

     if multipart?
       parts.each_with_index do |part, index|
       puts ""
       puts " parts[#{index}]"
       puts " content_type: #{part.content_type}"
       puts " multipart? #{part.multipart?}"

       header = part["content-type"]

       if part.multipart?
         puts " --multipartt--"
         part.parts.each_with_index do |part2, index2|
          puts " part[#{index}][#{index2}]"
          puts " content_type: #{part2.content_type}"
          puts " body: #{part2.unquoted_body}"
       elsif header.nil?
         puts " --header nil--"
     elsif !attachment?(part)
       puts " --no multipart, no header nil, no attachment--"
       puts " content_type: #{part.content_type}"
       puts " body: #{part.unquoted_body}"
       puts " --no multipart, no header nil, attachment--"
       puts " content_type: #{part.content_type}"

       puts " --no multipart--"
       puts " content_type: #{content_type}"
       puts " body: #{unquoted_body}"

     puts "END"


Monday, January 26, 2009

Merb gets merged into Rails 3.0 !!

Ruby on Rails team broke the news: the alternative Ruby web application framework, Merb, will be merged into Ruby on Rails 3.0.

Merb, which was already closely patterned after Rails, brings performance, modularity, and better integration with alternative JavaScript and ORM frameworks to the table. The default Rails configuration will still be the "full stack" framework, which uses ActiveRecord and Prototype, but there will also be a "Rails Core" with the ability to opt into specific other (e.g. JavaScript or ORM) frameworks as desired.

The Merb team will be working with the Rails core team on a joint project. The plan is to merge in the things that made Merb different. This will make it possible to use Rails 3 for the same sorts of use-cases that were compelling for Merb users. Effectively, Merb 2 is Rails 3.

You can read more about here:

Saturday, January 24, 2009

Inline file upload - iframe - ajax - Ruby on Rails

In View

<% form_for(@images, :url => formatted_images_path(:format => 'js'), :html => { :multipart => true,:target => 'upload_frame' }) do |f| %>
<%= f.file_field :uploaded_data, :size => "50" %>
<%= f.submit :Submit %>
<% end %>
< id="'upload_frame'," name="upload_frame" style="width:1px;height:1px;border:0px" src = "about:blank">

in controller
def create
@image = Image.new
if @image.save
respond_to do |format|
format.js do
responds_to_parent do
render :update do |page|
page.replace_html 'imgupload', :partial => 'imageupload',:object => @images
page.visual_effect :highlight, "image_#{@image.id}"

Watermarking an image in Rails - Rmagick

class Image < ActiveRecord::Base

require 'RMagick'
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 4.megabytes,
:resize_to => '640x400>',
:thumbnails => { :thumb => '100x100>',:medium => '250x150' }


def watermark_image
dst = Magick::Image.read("#{RAILS_ROOT}/public/#{self.public_filename}").first
src = Magick::Image.read("#{RAILS_ROOT}/public/images/logo.gif").first
result = dst.composite(src, Magick::CenterGravity, Magick::HardLightCompositeOp)

Improving Rails Applications performance

I have done some research about improving Rails Applications performance. I would feel the the following few points need to be considered when we optimize rails applications for performance:

1) Avoid the use of dynamic URL generation (link_to, url_for) since rails needs to look up the routes table and that may take time. Just hard code the controller name and the action.

2) Try to avoid the excess use of helpers since it adds overhead.

3) You may consider to use Rails Bench to do some testing for you rails application performance.

4) You may consider to use memcached to cache your model and library computation results.

5) try to optimize your database queries. If you use ActiveRecord find, be careful from computation intensive sql queries that returns to you a lot of data that you may not need. The method find may run many select statements for you.

Contact Me for any help regarding rails/nodejs/php/mysql


Email *

Message *