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
Working with Ruby on Rails since july 2007. RoR web application development along with other technologies like LAMP.The reason to love programming with RoR is, it helps keep code simple, clean and nice… Also working with php/cakephp etc.
Tuesday, November 17, 2009
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
or
find ./ -name “.svn” -exec rm -rf {} \;
Source: http://www.rickhurst.co.uk/category/linux/
find ./ -name ".svn" | xargs rm -Rf
or
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.'
else
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)
end
end
# Do your Logic after getting details
mail.delete
end
pop.finish
end
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")
end
CTYPE_TO_EXT = {
'image/jpeg' => 'jpg',
'image/gif' => 'gif',
'image/png' => 'png',
'image/tiff' => 'tif'
}
def ext( mail )
CTYPE_TO_EXT[mail.content_type] || 'txt'
end
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
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
end
elsif !attachment?(part)
result = part.unquoted_body if part.content_type =~ /html/i
end
end
else
result = unquoted_body if content_type =~ /html/i
end
result
end
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}"
end
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}"
else
puts " --no multipart, no header nil, attachment--"
puts " content_type: #{part.content_type}"
end
end
else
puts " --no multipart--"
puts " content_type: #{content_type}"
puts " body: #{unquoted_body}"
end
puts "END"
end
end
end
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.'
else
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)
end
end
# Do your Logic after getting details
mail.delete
end
pop.finish
end
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")
end
CTYPE_TO_EXT = {
'image/jpeg' => 'jpg',
'image/gif' => 'gif',
'image/png' => 'png',
'image/tiff' => 'tif'
}
def ext( mail )
CTYPE_TO_EXT[mail.content_type] || 'txt'
end
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
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
end
elsif !attachment?(part)
result = part.unquoted_body if part.content_type =~ /html/i
end
end
else
result = unquoted_body if content_type =~ /html/i
end
result
end
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}"
end
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}"
else
puts " --no multipart, no header nil, attachment--"
puts " content_type: #{part.content_type}"
end
end
else
puts " --no multipart--"
puts " content_type: #{content_type}"
puts " body: #{unquoted_body}"
end
puts "END"
end
end
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:
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:
- http://weblog.rubyonrails.org/2008/12/23/merb-gets-merged-into-rails-3
- http://rubyonrails.org/merb
- http://yehudakatz.com/2008/12/23/rails-and-merb-merge/
- http://brainspl.at/articles/2008/12/23/merb-is-rails
- http://merbist.com/2008/12/23/rails-and-merb-merge/
- http://onrails.org/articles/2008/12/24/the-future-of-rails-rails-3-0
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| %>
Image
<%= 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}"
end
end
end
end
end
end
<% form_for(@images, :url => formatted_images_path(:format => 'js'), :html => { :multipart => true,:target => 'upload_frame' }) do |f| %>
Image
<%= 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}"
end
end
end
end
end
end
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' }
validates_as_attachment
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)
result.write("#{RAILS_ROOT}/public/#{self.public_filename}")
end
require 'RMagick'
has_attachment :content_type => :image,
:storage => :file_system,
:max_size => 4.megabytes,
:resize_to => '640x400>',
:thumbnails => { :thumb => '100x100>',:medium => '250x150' }
validates_as_attachment
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)
result.write("#{RAILS_ROOT}/public/#{self.public_filename}")
end
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.
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.
Subscribe to:
Posts (Atom)