rss
twitter
    Find out what I'm doing, Follow Me :)

Image Rotation with Jquery Plugin

It is a great plugin for rotation of images with the help of Jquery.

This plugin is a copy of mooTools implementation made by Cédric for this library, check it out at http://www.piksite.com/mRotate/ (IT might be outdated!)

Download:

jQueryRotate.js

Description:


This is an final product of a Wilq32.PhotoEffect Snippet. Actually you can use this simple and tiny script to get effect of rotated images directly from client side (for ex. user generated content), and animate them using own functions.


Usage:

jQuery(imgElement).rotate(angleValue)

jQuery(imgElement).rotate(parameters)

jQuery(imgElement).rotateAnimation(parameters)

jQuery(imgElement).rotateAnimation(parameters)


Returns:


jQueryRotateElement - !!! NOTICE !!! function return rotateElement instance to help connect events with actually created 'rotation' element.


Parameters:

  • ({angle:angleValue,


  • [animateAngle:animateAngleValue],


  • [maxAngle:maxAngleValue],


  • [minAngle:minAngleValue],


  • [callback:callbackFunction],


    • [bind:[{event: function},{event:function} ] })

jQuery(imgElement).rotateAnimation


Where:

  • - angleValue - clockwise rotation given in degrees,

  • - [animateAngleValue] - optional parameter, animate rotating into this value,

  • - [maxAngleValue] - optional parameter, maximum angle possible for animation,

  • - [minAngleValue] - optional parameter, minimum angle possible for animation,

  • - [callbackFunction] - optional function to run after animation complete,

  • - [bind: [ {event: function}...] -optional parameter, list of events binded to newly created rotateable object
Examples:

$(document).ready(function()
{
$('#image').rotate(-25);


});


vikas nandal


$(document).ready(function()
{
$('#image2').rotate({angle:5});
});





$(document).ready(function()
{
var rot=$('#image3').rotate({maxAngle:50,minAngle:-55,
bind:
[
{"mouseover":function(){rot[0].rotateAnimation(50);}},
{"mouseout":function(){rot[0].rotateAnimation(-50);}}
]
});
});

Ajax pagination with mislav's will_paginate

Installation of mislav's will_paginate.

In previous rails versions the PaginationHelper was in bilt but in later versions (Rails 2.0) it is deleted. There are two ways to install the will paginate.
  • use the gem(recommended)
  • install as Rails plugin using git

I have put that in the vender/gems folder.
Here is the process :

Gem Installation.

  1. Download the gem from the Git Hub :
  2. git clone git://github.com/mislav/will_paginate.git

  3. Put this in vender/gems folder.

  4. Put the following code in environment.rb file :

  5. config.gem "mislav-will_paginate", :version => "2.3.6", :lib => "will_paginate"
  6. Now in your controller write the code for pagination :


  7. def index
    @posts = Post.paginate(:all, :page => params[:page], :per_page => 6)
    respond_to do |format|
    format.html { }
    format.js {
    render :update do |page|
    page.replace_html 'all-posts', :partial => @posts
    page.replace_html 'pagination', :partial => 'pagination',
    :locals => {:collection => @posts}
    end
    }
    format.xml { render :xml => @posts }
    end
    end



    There will be two partials one for showing the posts and other for the pagination helper.

  8. The pagination partial will look like this : -
  9. pagination.html.erb :-

    <%= will_paginate collection, :remote => "true", :params => { :paginated => true } %>



  10. The index.rhtml file will be :


  11. index.html.erb :-



    <%= render :partial => @posts %>





How to export data using MS word or MS excel

Its also very easy to export data to doc format or xls format. There is no plugin or gem required for that.
The procedure is :

FOR XLS FORMAT:


def export
headers['Content-Type'] = "application/vnd.ms-excel"
headers['Content-Disposition'] = 'attachment; filename="excel-export.xls"'
headers['Cache-Control'] = ''
@records = Record.find(:all)
end


and

FOR DOC FORMAT


def export
headers['Content-Type'] = "application/vnd.ms-word"
headers['Content-Disposition'] = 'attachment; filename="excel-export.doc"'
headers['Cache-Control'] = ''
@records = Record.find(:all)
end

How to export data to CSV In Ruby on Rails

The exporting of data to CSV in Rails is very easy just like snitching icecream from 2 year baby. You just need to install a Gem for it and a method and its done.

The procedure is written below:-

1. install the fastercsv gem :-

sudo gem install fastercsv


2. now in the controller use this gem and copy the method in the bottom of your controller and also use CSV as written:-


class ArticlesController < ApplicationController

require 'fastercsv'
......
.
.
.

def show_users
@users = User.find(:all)
stream_csv do |csv|
csv << ["Show all the users in excel"]
csv << [""]
csv << ["ID" ,"Name" ,"Address" ,"Email"]
@users.each do |u|
csv << [u.id, u.name, u.address, u.email]
end
end

end

private
def stream_csv

filename = action_name + ".csv"

#this is required if you want this to work with IE
if request.env['HTTP_USER_AGENT'] =~ /msie/i
headers['Pragma'] = 'public'
headers["Content-type"] = "text/plain"
headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
headers['Expires'] = "0"
else
headers["Content-Type"] ||= 'text/csv'
headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""
end

render :text => Proc.new { |response, output|
csv = FasterCSV.new(output, :row_sep => "\r\n")
yield csv
}
end

end




and its done. You have exported data to excel sheet .

Installing Tata Indicom Modem in Ubuntu

It is needed but Tata Indicom doesn't provide any CD to run USB VDATA card to run in Ubuntu(Linux)

SO try these steps to install it in Ubuntu.

1. Open a terminal window.
2. Enter as an root (type su (press enter) your password.)
3. Then use vi or nano or gedit to edit/create the following file /etc/wvdial.conf .
4. Enter the following text into it.
[Modem0]
Modem=/dev/ttyUSB0
Baud=115200
SetVolume=0
Dial Command = ATDT
init1=ATZ
init2=AT+CRM=1
FlowControl= Hardware (CRTSCTS)
[Dialer tata]
Username= internet
Password= internet
Phone=#777
Stupid Mode= 1
Inherits = Modem0


5. Then create /etc/resolv.conf using vi or nano with sudo
type: nameserver 202.138.103.100
nameserver 202.138.96.2

6. THIS SPECIFIES THE PRIMARY AND SECONDARY DNS SERVERS.
Then in terminal type
sudo wvdial tata

So now your Tata Indicom Vdata Card is installed.

Similary you can install USB Modem of tata indiacom :

just open the terminal
and enter as a root
and vi or nano or gedit to edit/create the following file /etc/wvdial.conf .

[Dialer Defaults]
Modem = /dev/ttyACM0
Baud = 460800
Init1 = ATZ
Init2 = ATQ0 V1 E1 S0=0 &C1 &D2
+FCLASS=0
ISDN = 0
Modem Type = USB Modem
Phone = #777
Username = internet
Password = internet
stupid mode = 1



save it and run sudo wvdial

If you are a reliance user then
just change the phone ,username and password

Phone = #777
Username =
Password =


and Bingoo!!!

Uploading video using Mongrel_upload progress and Active Messaging

ActiveMessaging is an attempt to bring the simplicity and elegance of rails development to the world of messaging. Messaging, (or event-driven architecture) is widely used for enterprise integration, with frameworks such as Java's JMS, and products such as ActiveMQ, Tibco, IBM MQSeries, etc.

Download Active Messaging from SVN:

script/plugin install http://activemessaging.googlecode.com/svn/trunk/plugins/activemessaging

For the protocol, ActiveMessaging supports Stomp: Streaming Text-Oriented Messaging Protocol. Stomp is a messaging standard to exchange text based messages over wire connections, usually tcp/ip.

TO install the stomp install the gems:

Assuming you have Rails 1.1+ and MySql already, you'll also need 2 more RubyGems: daemons and Stomp:

sudo gem install daemons
sudo gem install stomp


Download Apache ActiveMQ from
http://activemq.apache.org/

Apache ActiveMQ is the most popular and powerful open source Message Broker and Enterprise Integration Patterns provider.

cd /usr/local/src
#unix and cygwin
wget http://people.apache.org/repo/m2-snapshot-repository/org/apache/activemq/apache-activemq/4.2-SNAPSHOT/apache-activemq-4.2-20070221.081507-10-src.tar.gz
#os x
curl -O http://people.apache.org/repo/m2-snapshot-repository/org/apache/activemq/apache-activemq/4.2-SNAPSHOT/apache-activemq-4.2-20070221.081507-10-src.tar.gz

cd ..
tar xvfz apache-activemq-4.2-20070221.081507-10-src.tar.gz
cd apache-activemq-4.2-incubator-SNAPSHOT
./bin/activemq




Download the sample application using ActiveMessaging and Amazon S3

http://blog.snowonrails.com/articles/2007/05/31/how-to-build-a-mini-youtube-using-activemessaging-plugin-and-amazon-s3



Mongrel Upload Demo
http://itblog.mcgeecorp.com/2007/5/15/mongrel-upload-progress-demo


Install the mongrel_upload progress plugin

gem install mongrel --source=http://mongrel.rubyforge.org/releases/

svn co svn://rubyforge.org/var/svn/mongrel/trunk/projects/mongrel_upload_progress
cd mongrel_upload_progress
rake install



Mongrel_upload useses respond_to_parent function and also mongrel_upload_progress.conf file

Now Active Messaging video uploading as give by the



uses the Amazon S3 address for string the file address. And for that you need API key
and for sure its not free. So I have discovered the alternate to use the localhost for stroing the images.

Its very simple..

In the model video.rb use the following:

VIDEO_BASE = "#{RAILS_ROOT}/public/videos"
VIDEO_UPLOADED = VIDEO_BASE+"/uploaded/"
VIDEO_CONVERTED = VIDEO_BASE+"/converted/"


def video=(video_file)
@temp_file = video_file
self.file_name = video_file.original_filename
self.ext = self.file_name.split('.').last
end

def video_upload_path(file_name=self.file_name)
VIDEO_UPLOADED + file_name
end

def video_convert_path(file_name=convert_file_name)
VIDEO_CONVERTED + "#{id}/"+ file_name
end

def convert_file_name
"#{get_original_filename_without_ext}.flv"
end

def before_create
logger.debug("In before save of video.rb, video_upload_path is:"+video_upload_path+" and video_convert_path is:"+video_convert_path)
save_upload_file
end

def after_create
create_dir
end

private
def get_original_filename_without_ext(filename=self.file_name)
filename.sub(/(.\w+\z)/,"")
end

def create_dir
if !File.exist?(VIDEO_CONVERTED+"#{id}/")
Dir.mkdir(VIDEO_CONVERTED+"#{id}/")
end
end

def save_upload_file
if !File.exist?(VIDEO_BASE)
Dir.mkdir(VIDEO_BASE)
end
if !File.exist?(VIDEO_UPLOADED)
Dir.mkdir(VIDEO_UPLOADED)
end
if !File.exist?(VIDEO_CONVERTED+"#{id}/")
Dir.mkdir(VIDEO_CONVERTED+"#{id}/")
end

File.open(video_upload_path,"wb") do |f|
f.write(@temp_file.read)
end
end



In the broker.yml file use the following settings:

adapter: stomp
login: ""
passcode: ""
host: localhost
port: 61613
reliable: true
reconnectDelay: 5



Now its done.

Start your newly created application as like that:

Start ActiveMQ
Start Rails with mongrel_upload_progress config file
Start Poller
Start DRB server

Bingoooooooooo.

Adding Tags without spaces

Some times it is needed to addd the tag using acts_as_taggable plugin that you don't need spaces while creating tags. Means the tags are seprated not by spaces but with commas(,). For the we have to modify the code in the acts_as_taggable plugin.

Just open the file \vendor\plugins\acts_as_taggable\lib\tag.rb

We have to midify the method self.parse(list)

with the following code:

def self.parse(list)
unless list.kind_of? Array
tag_names = []

# first, pull out the quoted tags
list.gsub!(/"(.*?)"s*/ ) { tag_names << $1; "" }

# then, replace all commas with a space
list.gsub!(/,/, " ")

# then, get whatever's left
tag_names.concat list.split(/s/)

# strip whitespace from the names
tag_names = tag_names.map { |t| t.strip }

# delete any blank tag names
tag_names = tag_names.delete_if { |t| t.empty? }

return tag_names
else
tag_names = list.collect {|tag| tag.nil? ? nil : tag.to_s}
return tag_names.compact
end
end

Creating Tag Cloud using acts_as_taggable

In you rails application if you are using acts_as_taggable plugin for creating tags you often need to use tag cloud. To create a tag cloud using acts_as_taggable plugin its simple. We need to add some code in tagaable plugin.

It is as follows:
Add a new method in the Tag model provided by the acts_as_taggable plugin. Open the vendor/plugins/acts_as_taggable/lib/tag.rb file and add the following method:

def self.tags(options = {})
query = "select tags.id, name, count(*) as count"
query << " from taggings, tags"
query << " where tags.id = tag_id"
query << " group by tag_id"
query << " order by #{options[:order]}" if options[:order] != nil
query << " limit #{options[:limit]}" if options[:limit] != nil
tags = Tag.find_by_sql(query)
end



This method will return the id, name, and usage count for each tag. This method also provides a way to limit and order the tags. Once we have added the new method in the Tag model we will need to add a method to the application helper which will help in selecting the right style class for each tag. Add the following function to app/helpers/application_helper.rb:


def tag_cloud(tags, classes)
max, min = 0, 0
tags.each { |t|
max = t.count.to_i if t.count.to_i > max
min = t.count.to_i if t.count.to_i < min
}

divisor = ((max - min) / classes.size) + 1

tags.each { |t|
yield t.name, classes[(t.count.to_i - min) / divisor]
}
end


Now focus on the controller and view. In the controller you can use the following bit of code to get the the first one hundred tags order by name:

@tags = Tag.tags(:limit => 100, :order => "name desc")


In the view we will use the tag_cloud method so that it will select the right css class based on the tag usage count. Here is the view code:
<% tag_cloud @tags, %w(nube1 nube2 nube3 nube4 nube5) do |name, css_class| %>
<%= link_to name, {:action => :tag, :id => name},
:class => css_class %>
<% end %>


In the Css file add the following line.

.nube1,.nube1:hover, .nube1:active, .nube1:visited {text-decoration:underline;font-size: 1.2em;font-weight: 100;margin-left:1px;color:#000000;}
.nube2,.nube2:hover, .nube2:active, .nube2:visited {text-decoration:underline;font-size: 1.4em;font-weight: 300;margin-left:1px;color:#000000;}
.nube3,.nube3:hover, .nube3:active, .nube3:visited {text-decoration:underline;font-size: 1.6em;font-weight: 500;margin-left:1px;color:#000000;}
.nube4,.nube4:hover, .nube4:active, .nube4:visited {text-decoration:underline;font-size: 1.9em;font-weight: 700;margin-left:1px;color:#000000;}
.nube5,.nube5:hover, .nube5:active, .nube5:visited {text-decoration:underline;font-size: 2.2em;font-weight: 900;margin-left:1px;color:#000000;}
.nube6,.nube6:hover, .nube6:active, .nube6:visited {text-decoration:underline;font-size: 2.5em;font-weight: 1100;margin-left:1px;color:#000000;}