Friday, December 31, 2010

Rails Calendar date select without Image

Hi.

calendar_date_select plugin uses the following tag,

<%= calendar_date_select_tag "start_date", Time.now, :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>
<script>
jQuery(function() {
jQuery("#datepicker").datepicker();
});
</script>

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.

http://jqueryui.com/themeroller/

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) || {}
super
end

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

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

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

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 { }
end

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 {
padding:0.3em;
text-align:right;
}
.pagination a, .pagination span {
padding:0.2em 0.5em;
}
.pagination span.disabled {
color:#AAAAAA;
}
.pagination span.current {
color:#8FBF5D;
font-weight:bold;
}
.pagination a {
border:1px solid #DDDDDD;
color:#0063DC;
text-decoration:none;
}
.pagination a:hover, .pagination a:focus {
-moz-background-clip:border;
-moz-background-inline-policy:continuous;
-moz-background-origin:padding;
background:#0063DC none repeat scroll 0 0;
border-color:#003366;
color:white;
}
.pagination .page_info {
color:#AAAAAA;
padding-top:0.8em;
}
.pagination .prev_page, .pagination .next_page {
border-width:1px;
}

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 https://github.com/rails/auto_complete for doing this and i made it in 5-10 mins.

Install plugin :

ruby script/plugin install git://github.com/rails/auto_complete.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'
end

Search Query in model:

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

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}"
end

In auto_complete_result method:

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

Regards,
Srikanth

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?
(1..5).include?(wday)
end

check ..

d = Date.today
=> Mon, 04 Oct 2010
d.weekday?
=> true
d = Date.today - 1
=> Sun, 03 Oct 2010
d.weekday?
=> 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 http://nokogiri.org/tutorials/installing_nokogiri.html 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:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/usr/local/bin/ruby
--with-zlib-dir
--without-zlib-dir
--with-zlib-include
--without-zlib-include=${zlib-dir}/include
--with-zlib-lib
--without-zlib-lib=${zlib-dir}/lib
--with-iconv-dir
--without-iconv-dir
--with-iconv-include
--without-iconv-include=${iconv-dir}/include
--with-iconv-lib
--without-iconv-lib=${iconv-dir}/lib
--with-xml2-dir
--without-xml2-dir
--with-xml2-include
--without-xml2-include=${xml2-dir}/include
--with-xml2-lib
--without-xml2-lib=${xml2-dir}/lib
--with-xslt-dir
--without-xslt-dir
--with-xslt-include
--without-xslt-include=${xslt-dir}/include
--with-xslt-lib
--without-xslt-lib=${xslt-dir}/lib


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



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 - http://axonflux.com/curb-install-problems-on-ubunt

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"

example,

def signup_notification(recipient)
recipients recipient.email_address_with_name
subject "New account information"
from "system@example.com"
content_type "text/html"
end

cheers,
Sri

Monday, August 30, 2010

select box Send Id, display name..

Hi,

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)

--
sri.

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;" %>

-
Sri

Friday, July 23, 2010

You are being redirected

Hi,

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..

Thanks,
Srikanth

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"
@session[:user].remember_me
cookies[:auth_token] = { :value => @session[:user].remember_token , :expires => @session[:user].remember_token_expires }
end
redirect_back_or_default :controller => "time"
else
flash.now['notice'] = "Login unsuccessful"
@login = @params[:user_login]
end
end
end

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


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? && Time.now < user.remember_token_expires
@session[:user] = user
end
end
end

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.email}--#{self.remember_token_expires}")
self.password = "" # This bypasses password encryption, thus leaving password intact
self.save_with_validation(false)
end

def forget_me
self.remember_token_expires = nil
self.remember_token = nil
self.password = "" # This bypasses password encryption, thus leaving password intact
self.save_with_validation(false)
end
end

Wednesday, June 23, 2010

FaceBook Javascript SDK Like button examples

<h1>Defaults</h1>
<fb:like></fb:like>

<h1>Explicit href</h1>
<fb:like href="http://fbrell.com"></fb:like>

<h1>Custom Font</h1>
<fb:like font="trebuchet ms" href="http://fbrell.com"></fb:like>

<h1>Disable Faces</h1>
<fb:like show_faces="no" href="http://fbrell.com"></fb:like>

<h1>Button Count</h1>
<fb:like layout="button_count" href="http://fbrell.com"></fb:like>

<h1>Narrow</h1>
<fb:like width="200" href="http://fbrell.com"></fb:like>

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

<h1>Recommend</h1>
<fb:like href="http://fbrell.com"></fb:like>

<h1>Dark</h1>
<div style="background-color: black; padding: 10px;">
<fb:like colorscheme="dark" href="http://fbrell.com"></fb:like>
</div>

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

To Subscribe the likes

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


Source: http://developers.facebook.com/tools/console/ -> 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="http://www.google.com" />
<area shape="rect" coords="8,46,219,59" href="http://yahoo.com />
</map>

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 = Net::HTTP.new('facebook.com', 443)
http.use_ssl = true
path = "/oauth/access_token"
data = 'id=123456'
resp, data = http.post(path, data)
puts resp.inspect
puts data.inspect

Thanks,
Srikanth

Friday, May 7, 2010

Make ll command working in linux

Hi,

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.

Cheers,

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

Hi

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;

Thanks,
Sri

sending ajax request in rails

Hi

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;

Thanks,
Sri

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


Thanks,
Srikanth

Friday, April 2, 2010

Thinking sphinx

Hi,

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:
http://freelancing-god.github.com/ts/en/advanced_config.html
Generating Configuration to /home/srikanth/projects/
thisproject/config/development.sphinx.conf


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

You can get sphinx at http://sphinxsearch.com/


2) After I Install sphinx, when I start it
srikanth@client30:~/projects/
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 :):)

Thanks,
Srikanth

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"/>
<script>
function clearDefaultText(field){

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

}
</script>

Tuesday, March 23, 2010

Embed Flash - swf file in website

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,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="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="293" height="275"></embed>
</object>

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

21-3-2010





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.

<%= f.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
username@server
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
dumpfile.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
exit
mysql -u user -p dbname <
dumpfile.sql


Monday, February 1, 2010

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

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

Solution
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 - http://www.42.mach7x.com/2009/11/24/youre-in-the-middle-of-a-conflicted-merge-git/

Tuesday, January 19, 2010

Generate random texts

Hi,
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)] }
end

Thanks,
sri

Wednesday, January 13, 2010

'Include' in rails query

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

Admin:

belongs_to :user

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.

Hence,

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


I felt this easy than sqls, & interesting

Select Helper Methods in Rails

Hi,

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

http://shiningthrough.co.uk/Select-helper-methods-in-Ruby-on-Rails

Thanks,
Srikanth



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