Thursday, June 24, 2010

Get Session Data Available in Models - Ruby on Rails

Sometimes we really need session variables inside model. But as the rails framework defines (MVC) pattern. 

This pattern separates the context of the Web Application (Controller,View) from the Model. Model contains business logic of the web application. The Controller handles the interactions between the View and the Model. 

So you can not access sessions directly in your model. You can crack it by following way.

Create one module 
module Utility
  def current_user
    Thread.current[:user]
  end
 
  def self.current_user=(user)
    Thread.current[:user] = user
  end
end
 
Add following in application controller
 
class ApplicationController < ActionController::Base
  include Utility
  before_filter :set_user_session
 
  protected
  def set_user_session
    Utility.current_user = session[:user]
  end
end
 
And now get it in your model
 
class Account < ActiveRecord::Base
  include Utility
 
  def before_create
    unless allowed?(current_user)
      return false 
    end
  end
end
 
 

Tuesday, May 4, 2010

fetch all controllers and actions of the application

dirs = Dir.new("#{RAILS_ROOT}/app/controllers").entries
controller_hash = {}
dirs.each do |controller|
  if controller =~ /_controller/
    path = RAILS_ROOT + '/app/controllers/' + controller
    con = File.read(path).split('def ')
    con.delete_at(0)
    my_hash = Hash.new
    actions = con.collect{|c| c.gsub("\r","~").gsub("\n","~").split("~")[0].strip}
    controller_name = controller.gsub('.rb','')
    my_hash = {controller_name.to_s => actions}
    controller_hash = my_hash.merge(controller_hash)
  end
end
puts controller_hash.inspect

Friday, February 5, 2010

How to generate an SSH key in Linux?

You can generate a key in Linux using the ssh-keygen command.
You can run it in command line. You will be asked for a file in which the key should be saved to and for a passphrase (password) for the key:
This command will generate id_rsa public and private keys.

If you need to generate id_dsa keys then you need to run ssh-keygen -t dsa

Thursday, January 28, 2010

cannot open shared object file: No such file or directory

I got below error while i tried to run my application in fedora

libMagickCore.so.2: cannot open shared object file: No such file or directory – /usr/lib/ruby/gems/1.8/gems/rmagick-2.8.0/lib/RMagick2.so

To get solved of this error i executed
ldconfig /usr/local/lib

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

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

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

Name

Email *

Message *