Thursday, February 17, 2011

Will Paginate - Array Pagination

Wanna paginate an Array using will paginate.. Here is how i did..

Add this as method,

Array.class_eval do
def paginate(page=1, per_page=15)
pagination_array = WillPaginate::Collection.new(page, per_page, self.size)
start_index = pagination_array.offset
end_index = start_index + (per_page - 1)
array_to_concat = self[start_index..end_index]
array_to_concat.nil? ? [] : pagination_array.concat(array_to_concat)
end
end

And with the array @results do @results.paginate

reference: http://www.devchix.com/2007/07/23/will_paginate-array/

Regards,
Srikanth
Learn to Program with Ruby | Ruby Pocket Reference

Wednesday, February 16, 2011

Ruby Sorting Manually by created at

Hi,

I have used this for sorting manually.

@results.sort{|x, y| x.send(:created_at) <=> y.send(:created_at)}

P.S. @results is an array tht has many records.

Concepts and Code

Tuesday, February 15, 2011

Rails + Google Map V3 with Marker, Bounds

Hi I have used this function to load Google map with Marker and bounds.

function initialize(lat, lon, div_id) {
var myLatlng = new google.maps.LatLng(lat, lon);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var bounds = new google.maps.LatLngBounds ();
var map = new google.maps.Map(document.getElementById(div_id), myOptions);
var trucklatlng = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker({
position: trucklatlng,
map: map,
title:"Assist"
});
var LatLngListFake1 = new google.maps.LatLng(lat + 0.005 , lon + 0.005);
var LatLngListFake2 = new google.maps.LatLng(lat - 0.005, lon - 0.005);
bounds.extend(LatLngListFake1);
bounds.extend(LatLngListFake2);
map.fitBounds (bounds);
}

In the View File:

Just call,

<script>initialize(lat, lon, div_id)</script>

Thursday, February 3, 2011

Exporting as CSV file in RAILS.

I have used Fastercsv gem to generate csv data and used send_data method..

def create_csv
@customers = Customer.all
csv_string = FasterCSV.generate do |csv|
csv << ["First Name", "Last Name", "Email", "Home Phone", "Alternate Phone", "Address Line1", "Address Line2", "City", "State", "Zip"]
@customers.each do |customer|
csv << [customer.firstname, customer.lastname, customer.email, customer.home_phone_number, customer.cell_phone_number, customer.address_line1, customer.address_line2, customer.city, customer.state, customer.zip]
end
end
send_data csv_string, :filename => "customers.csv" , :type=>"text/csv"
end