Friday, December 31, 2010

Rails Calendar date select without Image


calendar_date_select plugin uses the following tag,

<%= calendar_date_select_tag "start_date",, :size => 15 %>

The above tag gives a text box and an Image. Which i really don't need.

I have called the onclick function which was written in the image onclick with text box as follows,

<input type="text" name="start_date" onclick="new CalendarDateSelect( this, {year_range:10} );" />

Date Select work fine now with image.

Monday, December 27, 2010

MiniMagick - undefined method `output'

I have got error like this in attachment fu while uploading image and creating thumbnail,

NoMethodError (undefined method `output' for #<MiniMagick::CommandBuilder:0xb14dde4>):

I changed my Minimagick gem version to 1.2.5 and things worked fine..

Thursday, December 9, 2010

jQuery UI datepicker in Rails

I have spent lot of time in making this. The problem was there was conflict in the prototype & Jquery. This is how i did it,

Step 1:

Download jquery.ui.datepicker.js from jquery UI and add it in Javascripts folder.

Step 2 :

Add these in Layout,

<script src="/javascripts/jquery.js" type="text/javascript"></script>
<script src="/javascripts/jquery.ui.datepicker.js"></script>
jQuery(function() {

Note: instead of $(function) i have used jQuery(function)

Step 3 :

Then the View file, use,
<%= text_field_tag "datepicker" %>

Note :

If you get this error, "jquery ui $(input).zIndex is not a function"

1. Go to the datepicker JS & comment out the line where you get the error.
2. Add .ui-datepicker {z-index: 3000;} in ur stylesheet

Wednesday, December 8, 2010

Design your Site with Jquery UI

Jquery UI themeroller gives various themes and also we can customize and download.

It also gives various options like Datepicker, Accordian, Autocomplete etc.

Just select your theme, customize if you want & click Download Theme. Things will be in your hand.

Will Paginate Ajax pagination

I have gone through many articles on how to use Ajax pagination with will_paginate.

Here is how i did & it worked for me,

Step 1 :
Create a helper called remote_link_renderer.rb and use the following code,

class RemoteLinkRenderer < WillPaginate::LinkRenderer
def prepare(collection, options, template)
@remote = options.delete(:remote) || {}

def page_link(page, text, attributes = {})
@template.link_to_remote(text, {:url => url_for(page), :method => :get}.merge(@remote), attributes)

Step 2:
Make the view file table in a partial(_units.html.erb),

<div id="units">
<%= render :partial => "units" %>

Step 3 :

And in the partial _units.html.erb add will paginate code,
<%= will_paginate @units, :renderer => 'RemoteLinkRenderer' , :remote => { :update => 'units'} %>

Step 4 :

In the controller use:

respond_to do |format|
format.js { render :partial => 'units' }
format.html { }

Now Pagination works without refreshing the page.

Will paginate pagination style

Pagination using will paginate comes with div class "pagination"

Copy & paste the below code in css file, to make the pagination look a better.

.pagination {
.pagination a, .pagination span {
padding:0.2em 0.5em;
.pagination span.disabled {
.pagination span.current {
.pagination a {
border:1px solid #DDDDDD;
.pagination a:hover, .pagination a:focus {
background:#0063DC none repeat scroll 0 0;
.pagination .page_info {
.pagination .prev_page, .pagination .next_page {

Tuesday, December 7, 2010

Send Ajax request after Auto Complete text box - after_update_element

Continuation for my previous post about Auto complete plugin

I have used after_update_element to send the value that is selected in the Auto complete

<%= text_field_with_auto_complete 'phonenumber', 'to',{:size=>25, :class=> "text ui-widget-content ui-corner-all", :value=>@service_order.phonenumber}, {:skip_style => false, :after_update_element=> "function(element,value){new Ajax.Request('/controller/action', {asynchronous:true, evalScripts:true, method:'get', parameters:'number=' + $('phonenumber_to').value }); return false;
}"} %>

Friday, November 26, 2010

Auto Complete Text Box in Rails

Found an Awesome plugin for doing this and i made it in 5-10 mins.

Install plugin :

ruby script/plugin install git://

Use in HTML for Text field:
<%= text_field_with_auto_complete 'phonenumber', 'to',{}, :skip_style => false %>

Controller :

skip_before_filter :verify_authenticity_token, :only => [:auto_complete_for_phonenumber_to]

def auto_complete_for_phonenumber_to
phonenumber = params[:phonenumber][:to]
@phones = CustomerPhone.phonenumber_search(phonenumber)
render :partial => 'phonenumbers'

Search Query in model:

def self.phonenumber_search(keyword)
find(:all, :conditions=>["phonenumber like ?", "%#{keyword}%"])

View :

Create Partial : "_phone_number.html.erb"

<%= auto_complete_result @phones, :phonenumber %>

Restart your Server & Search. It works.

Note :
If you get undefined method "text_field_with_auto_complete" Error. It means you have not installed the plugin or have not restarted server.

Need to show more than one field ??
Here it is,

In View:
<%= auto_complete_result @phones, :show_field %>

In Model:

def show_field
"#{phonenumber}, #{name}, #{address}"

In auto_complete_result method:

items = { |entry| content_tag("li", phrase ? highlight(entry.show_field, phrase) : h(entry.show_field)) }


Books: Agile Web Development with Rails | Ruby on Rails For Dummies | Beginning Ruby: From Novice to Professional

Sunday, October 24, 2010

HTML stripping, Truncating string in Ruby, Rails

For Truncating String I have used 'truncate' rails helper method.

Ex) limiting to 10 characters
truncate("im srikanth glad to meet you", 10)
>> "im srik..."

For HTML stripping,

I have used gsub..

str.gsub(/<\/?[^>]*>/, "")

Sunday, October 3, 2010

Weekday or not..

You can Use this ,

def weekday?

check ..

d =
=> Mon, 04 Oct 2010
=> true
d = - 1
=> Sun, 03 Oct 2010
=> false

Tuesday, September 7, 2010

Installing pauldix-feedzirra

Hi when i tried to install pauldix-feedzirra, i got the below error.

sudo gem install pauldix-feedzirra
Building native extensions. This could take a while...
ERROR: Error installing pauldix-feedzirra:
ERROR: Failed to build gem native extension.

/usr/local/bin/ruby extconf.rb
checking for libxml/parser.h... yes
checking for libxslt/xslt.h... no
libxslt is missing. please visit for help with installing dependencies.
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.

Provided configuration options:

Gem files will remain installed in /usr/local/lib/ruby/gems/1.8/gems/nokogiri- for inspection.
Results logged to /usr/local/lib/ruby/gems/1.8/gems/nokogiri-

Then, I installed dependencies,

sudo apt-get install libxml2-dev
sudo apt-get install libxslt-dev

Now tried

sudo gem install pauldix-feedzirra

Worked fine!!

Problems in Installing Curb in ubuntu

Just install the below lib files,

sudo apt-get install libcurl3 libcurl3-gnutls libcurl4-openssl-dev

& then,

sudo gem install curb

It works!

-- source -

Sending HTML mail in rails

Hi pals,

If all the mails that you send are in HTML format. its simple. Specify this line in environment.rb

ActionMailer::Base.default_content_type = "text/html"

If only one action has to be in HTML mail, specify 'content_type' in that action.

content_type "text/html"


def signup_notification(recipient)
recipients recipient.email_address_with_name
subject "New account information"
from ""
content_type "text/html"


Monday, August 30, 2010

select box Send Id, display name..


used this to send the ID in params & display name in the select box.

select_tag "user", options_from_collection_for_select(User.all, :id, :name)

For adding option & showing selected params,

select_tag "user_id", "<option>select one</option>" + options_from_collection_for_select(User.all, :id, :name, params[:user_id].to_i)


Thursday, August 19, 2010

Image submit tag without border

Hi, I used image_submit_tag to submit my form. worked fine.. but the
image is displayed with border.

I used border => 0 but no use.

This is was code.

<%= image_submit_tag "../images/upload.png", :border => 0 %>

& This worked

<%= image_submit_tag "../images/upload.png", :style => "border: none;" %>


Friday, July 23, 2010

You are being redirected


I have got this page "You are being redirected", whenever i used redirect. I found out that I have written methods such as redirect_XXX, redirect_yyy. I have changed the method names & it works !!

Not using the rails keywords as method names, stops this bug..


Tuesday, June 29, 2010

Auto Login in rails

1. Remember me

When the user login and checks the “Remember me” checkbox, the :save_login parameter is set, the User instance remember_me method invoked and the :auth_token cookie set...

class AccountController < ApplicationController
def login
case @request.method
when :post
if @session[:user] = User.authenticate(@params[:user_login], @params[:user_password])
flash['notice'] = "Login successful"
if @params[:save_login] == "1"
cookies[:auth_token] = { :value => @session[:user].remember_token , :expires => @session[:user].remember_token_expires }
redirect_back_or_default :controller => "time"
else['notice'] = "Login unsuccessful"
@login = @params[:user_login]

def logout
@session[:user].forget_me if @session[:user]
@session[:user] = nil
cookies.delete :auth_token

2. login_from_cookie

The next time the user visits the website the “login_from_cookie” filter is triggered. This method checks that the user is not logged in and that the :auth_token cookie is set. If that’s the case the user matching the :auth_token is searched and the token_expiration verified the the user is automatically logged in. Et voila! I guess auto_login would be more appropriate as method name.

class ApplicationController < ActionController::Base
before_filter :login_from_cookie
def login_from_cookie
return unless cookies[:auth_token] && @session[:user].nil?
user = User.find_by_remember_token(cookies[:auth_token])
if user && !user.remember_token_expires.nil? && < user.remember_token_expires
@session[:user] = user

3. the User class

The User class has two methods to set and remove the token from the database. It’s pretty secure as from the token the user cannot be identified without having the salt, the email, and the token expiration, which is most unlikely to be recreated. It could be even more secure by just encrypting some random unique identifier. The only issue I encountered was that the user class always forces the password validation and encryption when saving. For now I just bypass validation and encryption when setting and clearing the remember_me token.

class User < ActiveRecord::Base
def remember_me
self.remember_token_expires = 2.weeks.from_now
self.remember_token = Digest::SHA1.hexdigest("#{salt}--#{}--#{self.remember_token_expires}")
self.password = "" # This bypasses password encryption, thus leaving password intact

def forget_me
self.remember_token_expires = nil
self.remember_token = nil
self.password = "" # This bypasses password encryption, thus leaving password intact

Wednesday, June 23, 2010

FaceBook Javascript SDK Like button examples


<h1>Explicit href</h1>
<fb:like href=""></fb:like>

<h1>Custom Font</h1>
<fb:like font="trebuchet ms" href=""></fb:like>

<h1>Disable Faces</h1>
<fb:like show_faces="no" href=""></fb:like>

<h1>Button Count</h1>
<fb:like layout="button_count" href=""></fb:like>

<fb:like width="200" href=""></fb:like>

<h1>Narrow no faces</h1>
<fb:like width="200" show_faces="no" href=""></fb:like>

<fb:like href=""></fb:like>

<div style="background-color: black; padding: 10px;">
<fb:like colorscheme="dark" href=""></fb:like>

<h1>Dark Button SuscribeCount</h1>
<fb:like layout="button_count" colorscheme="dark" href=""></fb:like>

To Subscribe the likes

// this will fire when any of the like widgets are "liked" by the user
FB.Event.subscribe('edge.create', function(href, widget) {'You liked ' + href, widget);

Source: -> examples

Monday, June 14, 2010

using map with html images

Wanna Use 1 image with 2 links??

<img src="/images/submit.png" width="219" height="59" border="0" usemap="#Map" />
<map name="Map" id="Map">
<area shape="rect" coords="17,15,218,44" href="" />
<area shape="rect" coords="8,46,219,59" href=" />

Thursday, June 3, 2010

Making a http/https post request

Spent an hour to find out how to send a https post request and this is how ..

require 'rubygems'
require 'net/http'
require 'net/https'
require 'uri'
http ='', 443)
http.use_ssl = true
path = "/oauth/access_token"
data = 'id=123456'
resp, data =, data)
puts resp.inspect
puts data.inspect


Friday, May 7, 2010

Make ll command working in linux


Today I ve learnt how to make ll working in linux from my friend swanand.

do the following,

gedit ~/.bashrc

alias ll='ls -l'

save the file & close it.

This makes ll working in all new tabs in console.


Tuesday, April 27, 2010

Checking requirements in Routes

Here by i have checked routes for domain_name with alpha-numeric.

map.home '/homes/:domain_name/:id',:controller=>'home', :action=>'new', :requirements => { :domain_name => /[A-Za-z0-9.]+/}

Friday, April 16, 2010

sending ajax request in rails


Just for syntax, used this for sending ajax request..

new Ajax.Request('/controller/action', {asynchronous:true, evalScripts:true, method:'get', parameters:'params1=' + param + '&param2=' + param + '&param3=' + param }); return false;


sending ajax request in rails


Just for syntax, used this for sending ajax request..

new Ajax.Request('/controller/action', {asynchronous:true, evalScripts:true, method:'get', parameters:'params1=' + param + '&param2=' + param + '&param3=' + param }); return false;


Thursday, April 8, 2010

Find Number of mp3 files in a directory

To Find Number of mp3 files in a directory,

I got this,

ls | grep .*.mp3 | wc -l


Friday, April 2, 2010

Thinking sphinx


This is a Great plugin in Rails for the search options. This comes with many inbuilt functionalities. There are many tutorials & Videos on how to work this.

But I struggled a lot in Installation.

1. I have installed the Thinking sphinx Plugin, But there was error

srikanth@client30:~/project$ rake thinking_sphinx:index

Sphinx cannot be found on your system. You may need to configure the following
settings in your config/sphinx.yml file:
* bin_path
* searchd_binary_name
* indexer_binary_name

For more information, read the documentation:
Generating Configuration to /home/srikanth/projects/

Solution : You will have to download and install the sphinx software. Thinking sphinx is only a wrapper around sphinx.

You can get sphinx at

2) After I Install sphinx, when I start it
my project$ rake thinking_sphinx:start
(in /home/srikanth/projects/my project)
Failed to start searchd daemon. Check /home/srikanth/projects/my project/log/searchd.log.
Failed to start searchd daemon. Check /home/srikanth/projects/my project/log/searchd.log

Solution: you need to configure and start the sphinx daemon

rake thinking_sphinx:configure
rake thinking_sphinx:start

& This should work.. It worked for me when i did

rake thinking_sphinx:start -t

Now everything works fine :):)


Wednesday, March 31, 2010

Add a text to text box, hide when it is clicked, show when clicked out

My Friend Ukesh gave me this code, thanks to him for saving my time.

<input name="q" id="search_text" type="text" value="- Search -" onfocus="clearDefaultText(this)" onblur="clearDefaultText(this)" style="background:none"/>
function clearDefaultText(field){

if (field.defaultValue == field.value) field.value = '';
else if (field.value == '') field.value = field.defaultValue;


Tuesday, March 23, 2010

Embed Flash - swf file in website

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase=",0,29,0" width="100" height="90">
<param name="movie" value="/videos/TGP.swf" />
<param name="quality" value="high" />
<embed src="/videos/TGP1.swf" quality="high" pluginspage="" type="application/x-shockwave-flash" width="293" height="275"></embed>

Sunday, March 21, 2010

ruby conference - India, Bangalore 2010

Me @ Ruby conf, Bangalore. - 20-3-2010

Seasons Hall, Royal orchid. The great man sitting is ola bini

priya, me, veera, shiv, uthiravel


updating blog & twitting

my Boss Senthil, Uthiravel, me

Very Excited meeting Obie Fernandez. wht a man!!! wht a programmer!!

Tuesday, March 2, 2010

Wednesday, February 24, 2010

select class not applied

<span style="font-size:130%;">Hi, previously my code was like this,

I tried much using, html_options, options, but class is not applied for select.

<%= 'difficulty', options_for_select({ "Easy" => "1", "Medium" => "3", "Hard" => "5"}, get_difficulty(@tour).to_s), :class =>'input_text' %>

& not other way i could find, i did by this way & it works fine now

<%= select :tour, :difficulty, { "Easy" => "1", "Medium" => "3", "Hard" => "5"}, {:selected=>get_difficulty(@tour).to_s}, :class=>"input_text" %>

Now class is applied!!!

Any other better way pls tel me,,.</span>

Tuesday, February 9, 2010

Getting a DB dump in local machine from server

Getting a DB dump in local machine from server..

1. Login into the server - ssh
2. mysqldump dbname -u dbusername -p > filename.sql
3. Logout of server

set path in local machine: Example - /home/Desktop

4. scp username@server:server_path/filename.sql

Thts it, now db dump is in local machine Desktop

Getting dump to local db,

mysql -u root -p
password: root
mysql> create database dbname
mysql -u user -p dbname <

Monday, February 1, 2010

You’re in the middle of a conflicted merge (git)

Trying to update (pull) in git causes the error ‘you’re in the middle of a conflicted merge’.

To be able to get out of this error try the followng:

  1. git reset –hard HEAD
  2. git fetch origin
  3. git reset –hard origin

to reset the state, and then you should be able to use git pull as normal.

This site helped me when i faced this problem -

Tuesday, January 19, 2010

Generate random texts

I have used this method to generate random texts ....

def rendom_password
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
newpass = ""
1.upto(7) { |i| newpass << chars[rand(chars.size-1)] }


Wednesday, January 13, 2010

'Include' in rails query

For getting a datum from 2 tables, I have used include as follows,


belongs_to :user


has_many :admins

There was a condition that i have to sort names of admins, where the names of admins will be in user table.


Admin.find(:all, :include=>"user", :order => "")

I felt this easy than sqls, & interesting

Select Helper Methods in Rails


Whenever i use a select Box in Rails, i have used this link.. This s really useful..


Tutorials: Ruby on Rails 3 Tutorial: Learn Rails by Example | Ajax on Rails | Rails 3 Way, The (2nd Edition) (Addison-Wesley Professional Ruby Series)