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

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;}

Observe_form for getting Live preview

You’d like to give your users the ability to see a live preview of their data
as they are editing it. You don’t want them to have to wait until they
submit a form. So that if there is any error it can be rectified.

Include the javascripts in the layouts.

<%= javascript_include_tag "default" %>

Now that we’ve got the necessary JavaScript libraries loaded, we’ll create
the model and controller.Suppose the controller name is Content and model name is Example. There are two fields in the table ('title' and 'body' )

Now in the model define the attribute accessor

class Example
attr_accessor :title, :body
end


We will create a new method

def new
@data= Example.new
end



Create the file, app/views/content/new.rhtml, and edit it to look like
the following.

<% form_for(:example,:url => {:action=>'create',:html => {:class=>'wufoo', :id => "form"} ) do |form| %>
<%= text_field :example, :title %>

<%= text_area :example, :body %>

<%= submit_tag "Save" %>
<% end %>
<%= observe_form "form",
:frequency => 5,
:update => "preview",
:complete => "Element.show(' preview' )",
:url => { :action => "preview" } %>


In the method preview we write

def preview
render :layout => false
end



The only job of the action code is to short circuit the application’s usual
rendering. Since we’re going to be updating the live-preview element of
our diary entry creation page with the full results of the preview( ) action,
we don’t want it returning a full HTML page.

The preview action’s view, in app/views/content/preview.rhtml should look
like this:

Form Preview


<%= params[:example][:title] %>


<%= textilize params[:example][:body] %>


That’s all there is to it! This view prints the entry’s title as an HTML
heading and then generates HTML output via the textilize( ) method. This
method uses the RedCloth library internally to transform very simple
text markup to HTML.

Ajax Editing using In-Place Form Editing

Your application has data that are often edited by
your users—usually very quickly. You want to give your users an easy
way to edit application data in place without having to open a separate
editing form.

Rails makes in-place editing easy with the script.aculo.us InPlaceEditor
control and accompanying helpers.

First create a model and controller.

Put JavaScript files in your views. Somewhere in the head
of your HTML document, you can call the following:

<%=javascript_include_tag :defaults%>

put the in place editor in you .rhtml file like this


<%=in_place_editor_field :contact, :name%>


In Controller write the following line
in_place_edit_for :contact, :name

and its done.

Ajax Pagination in rails

Ajax Pagination in Rails is very simple and DRY. You Just have to put ajax helper method in applicartion .rb. And its done. Here is the procedure.:

1) Put the following line of code in apllication_helper.rb file.

def ajax_pagination_links(paginator, options={})

options.merge!(ActionView::Helpers::PaginationHelper::DEFAULT_OPTIONS) {key, old, new old}
window_pages = paginator.current.window(options[:window_size]).pages
return if window_pages.length <= 1 unless options[:link_to_current_page] first, last = paginator.first, paginator.last returning html = '' do if options[:always_show_anchors] and not window_pages[0].first? html << update =""> options[:update], :url => { options[:name] => first }.update(options[:params] ))
html << ' ... ' if window_pages[0].number - first.number > 1
html << ' ' end window_pages.each do page if paginator.current == page && !options[:link_to_current_page] html << update =""> options[:update], :url => { options[:name] => page }.update(options[:params] ))
end
html << ' ' end if options[:always_show_anchors] && !window_pages.last.last? html << ' ... ' if last.number - window_pages[-1].number > 1
html << update =""> options[:update], :url => { options[:name] => last }.update( options[:params]))
end
end
end



2) Now in the controller in you method put the following code.

def user
@content_pages, @contentdata = paginate :users, :order =>"create_date DESC", :per_page => 6
if params[:page]
render :update do page
page[:center].replace_html :partial=>'user'
end
else
render :action=>'user'
end
end



3) And in the last just put these lines in the view part (rhtml) and its done.



<%=ajax_pagination_links @content_pages, {:params => {:search_query => @params[:search_query]} }%>