Date Formats in Ruby

  %a - The abbreviated weekday name (``Sun'')
  %A - The  full  weekday  name (``Sunday'')
  %b - The abbreviated month name (``Jan'')
  %B - The  full  month  name (``January'')
  %c - The preferred local date and time representation
  %d - Day of the month (01..31)
  %H - Hour of the day, 24-hour clock (00..23)
  %I - Hour of the day, 12-hour clock (01..12)
  %j - Day of the year (001..366)
  %m - Month of the year (01..12)
  %M - Minute of the hour (00..59)
  %p - Meridian indicator (``AM''  or  ``PM'')
  %S - Second of the minute (00..60)
  %U - Week  number  of the current year,
          starting with the first Sunday as the first
          day of the first week (00..53)
  %W - Week  number  of the current year,
          starting with the first Monday as the first
          day of the first week (00..53)
  %w - Day of the week (Sunday is 0, 0..6)
  %x - Preferred representation for the date alone, no time
  %X - Preferred representation for the time alone, no date
  %y - Year without a century (00..99)
  %Y - Year with century
  %Z - Time zone name
  %% - Literal ``%'' character
   t =
   t.strftime("Printed on %m/%d/%Y")   #=> "Printed on 04/09/2003"
   t.strftime("at %I:%M%p")            #=> "at 08:56AM

Bulk upload in ruby on rails.

A file upload, where we can upload a zip file and it will extract automatically can be done on the following way in Ruby On Rails.

As a first step install the gems, rubyzip and fastercsv.Then Perform the following code :-

<% form_for :file_upload,:url => {:controller=>'bulkupload',:action=>'upload_file'}, :html => { :multipart => true, :target => "frame", :id => "file_upload" } do |f| %>
<input type="file" name="file_upload_product[file_name]"/>
<input type="submit" value="Upload"/>

Now Open up your bulkupload controller and create method upload_file in that

require 'faster_csv'
require 'fileutils'
class BulkuploadProductController < ApplicationController
  def bulk_upload
      responds_to_parent do
       render :update do |page|
        page << "$('file_uploaded_id').value="
        page.replace_html 'upload_message',"<span class='heading4'>File has been moved to server. Please click submit to upload.</span>"
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Please Upload File</span>"
     rescue Exception=>e
      puts "ERROR :: bulkupload_products :: upload_file :: #{e.to_s}"
      responds_to_parent do
       render :update do |page|
        page.replace_html 'upload_message',"<span class='table_commands_row'>Some internal Error has occurred</span>"

Fetching Cotacts from Gmail, Yahoo and Hotmail

Hey guys, it’s pretty simple to fetch the contacts from gmail, yahoo or hotmail. Just 5-10 minutes is quite enough to be done. Follow the steps.

Step 1 :-

Install the gem contacts (sudo gem install contacts)

Step 2 :-

Add this line in the environment.rb

require ‘contacts’

Step 3 :-

Some coding part in controller on view


def invite_friends

@user = User.find(params[:id])

//Pass the params of user id, can be the current user id also.for eg, invite/invite_friends/1

//It does not have impact of fetching the contacts from gmail, yahoo or hotmail.

def import
@users = User.find(params[:id])
@sites = {“gmail”  => Contacts::Gmail, “yahoo” => Contacts::Yahoo, “hotmail” => Contacts::Hotmail}
@contacts = @sites[params[:from]].new(params[:login], params[:password]).contacts
@users , @no_users = [], []
@contacts.each do |contact|
if u = User.find(:first , :conditions => “email = ‘#{contact[1]}'” )
@users << u
@no_users << {:name => contact[0] , :email => contact[1]}
respond_to do |format|
format.html {render :template => ‘invite/_contact_list’, :layout => false}
format.xml {render : xml => @contacts.to_xml}

Create a folder named ‘invite’ on the views and create the following erb files.


<% form_tag :action => ‘import’, :id => @user do %>

<select name=”from” id=”from”>
<option value=””>Select Id</option>
<option value=”gmail”>Gmail</option>
<option value=”yahoo”>Yahoo</option>
<option value=”hotmail”>Hotmail</option>

<BR />
<p>Please Enter Your Email Address Below : <BR />
<input type=”text” name=”login”></p>
<p>Enter Your Password :<BR />
<input type=”password” name=”password”></p>

<p><h4>Note : we are not going to save your Password anywhere </h4></p>
<p><%= submit_tag ‘Find My Friends’ %>

<% end %>


<% for i in @contacts %>
<input type=”checkbox” name=”email[]” id=”email_<%= i %>” value=”<%= i %>” /><%= i %><br>
<% end %>

That’s it. Done. Any queries let me know.

Plugin for running MySQL common database tasks

Download the plugin and run the MySQL common database tasks like create, destroy, backup & restore.


./script/plugin install


rake db:mysql:create           # Create database (using database.yml config)
rake db:mysql:destroy          # Destroy database (using database.yml config)
rake db:mysql:backup           # Dump schema and data to an SQL file (/db/backup_YYYY_MM_DD.sql)
rake db:mysql:restore          # Load schema and data from an SQL file (/db/restore.sql)

Rails performance tip – using YSlow

Find out the performance of your rails site using yslow. YSlow requires the indispensable Firebug extension.

Download it from

YSlow checks your site in 13 scenarios as follows :-

  • Make Fewer HTTP Requests
  • Use a Content Delivery Network
  • Add an Expires Header
  • Gzip Components
  • Put CSS at the Top
  • Move Scripts to the Bottom
  • Avoid CSS Expressions
  • Make JavaScript and CSS External
  • Reduce DNS Lookups
  • Minify JavaScript
  • Avoid Redirects
  • Remove Duplicate Scripts and
  • Configure ETags

The easiest way to make fewer HTTP requests is to combine all JavaScript and CSS files into one. The asset packager plugin does exactly this, plus it will also compress the source files (in production mode) and correctly handles caching (without query string parameters).

Moving CSS to the top (within the head section) and moving JavaScript to the bottom of the page are both manual tasks that should be done in the layout templates (such as app/views/layouts/application.rhtml). Remember to use stylesheet_link_merged :base and javascript_include_merged :base rather than the default Rails helpers.

By using asset packager you can also verify that scripts are only included once – another performance hit otherwise!

Refer :-

AssetPackager in rails

AssetPackager is nothing but a JavaScript and CSS Asset Compression for Production Rails Apps.

When it comes time to deploy your new web application, instead of sending down a dozen javascript and css files full of formatting and comments, this Rails plugin makes it simple to merge and compress JavaScript and CSS down into one or more files, increasing speed and saving bandwidth.

Step 1 – Install and download the plugin

script/plugin install git://

Step 2 – Create asset_packages.yml file

rake asset:packager:create_yml

Now the file will be generated under the /config for the first time. You will need to reorder files under ‘base’ so dependencies are loaded in correct order. Feel free to rename or create new packages.

Step 3 – Run the below command to generate the compressed, merged versions for each package

rake asset:packager:build_all

Whenever you rearrange the yaml file, you’ll need to run this task again.


Javascript Examples:

Example calls

  • either by package name:
  <%= javascript_include_merged :base %>
  • or by the individual assets:
  <%= javascript_include_merged 'prototype', 'effects', 'controls', 'dragdrop', 'application' %>

Output in development:

  <script type="text/javascript" src="/javascripts/prototype.js"></script>
  <script type="text/javascript" src="/javascripts/effects.js"></script>
  <script type="text/javascript" src="/javascripts/controls.js"></script>
  <script type="text/javascript" src="/javascripts/dragdrop.js"></script>
  <script type="text/javascript" src="/javascripts/application.js"></script>

Output in production:

  <script type="text/javascript" src="/javascripts/base_packaged.js?123456789"></script>

Symbols work too, as does :defaults

  <%= javascript_include_merged :defaults %>
  <%= javascript_include_merged :foo, :bar %>

Stylesheet Examples

Example call:

  • either by package name:
  <%= stylesheet_link_merged :base %>
  • or by the individual assets:
  <%= stylesheet_link_merged 'screen', 'header' %>

Output in development:

  <link href="/stylesheets/screen.css" media="screen" rel="Stylesheet" type="text/css" />
  <link href="/stylesheets/header.css" media="screen" rel="Stylesheet" type="text/css" />

Output in production:

  <link href="/stylesheets/base_packaged.css?123456789" media="screen" rel="Stylesheet" type="text/css" />

recursive_symbolize_keys in ruby

Result of not using recursive_symbolize_keys, we are getting APP_CONFIG as a string

$>> APP_CONFIG = YAML.load_file(“#{RAILS_ROOT}/config/settings.yml”)[RAILS_ENV]

=> {“xpmm”=>{“admin_password”=>123, “admin”=>”admin”, “bosh_service”=>”/http-bind”, “muc_component”=>”conference.client381”, “bosh_host”=>”site”, “strophe_debug”=>false, “host”=>”client38”}, “site_url”=>”http://site&#8221;, “admin_email”=>””, “chat_host”=>””, “dropio_api_key”=>”aa6b700a23a69a6051802a6a6d134e8c5e76e02e”, “site_name”=>”site”}

Result of using recursive_symbolize_keys, we are getting APP_CONFIG as a Key–>Symbol format

$>>APP_CONFIG = YAML.load_file(“#{RAILS_ROOT}/config/settings.yml”)[RAILS_ENV].recursive_symbolize_keys!

=> {:dropio_api_key=>”aa6b700a23a69a6051802a6a6d134e8c5e76e02e”, :site_name=>”site”, : xpmm=>{:muc_component=>”conference.client381″, :bosh_host=>”site”, :strophe_debug=>false, :admin_password=>123, :host=>”client38″, :admin=>”admin”, :bosh_service=>”/http-bind”}, :site_url=>”http://site&#8221;, :admin_email=>””, :chat_host=>””}

To do that :-

in /config/initializers/load_config.rb

require “#{RAILS_ROOT}/lib/ruby_classes_extensions”
APP_CONFIG = YAML.load_file(“#{RAILS_ROOT}/config/settings.yml”)[RAILS_ENV].recursive_symbolize_keys!

in /lib/ruby_classes_extensions.rb

class Hash
def recursive_symbolize_keys!
symbolize_keys!{ | v | v.is_a?( Hash ) }.each{ | h | h.recursive_symbolize_keys! }