Saturday, December 3, 2011

Caching in Rails

Rails has wonderful inbuilt caching methods. This is how i implemented caching for a particular action. 

 Requirement : Cache a page for 12 hours. After 12 hrs Caching must expire.

  before_filter :clear_cache
  caches_action :index, :layout => false

def index  
    #code
    # Write expiry time to cache (12 hours)
    Rails.cache.write('expiry_time', Time.now + 12.hours)
end


def clear_cache
    #Fetch time from cache and check with current time
    t = Rails.cache.fetch('expiry_time') || Time.now
    t = Time.parse(t) if t.is_a?(String)
    # Expire action if current time > Cached time
    expire_action :action => :index if Time.now > t
 end

Thanks!

Tuesday, November 8, 2011

Roles implemented with easy_roles plugin

 
Step 1 : Install Plugin
script/plugin install git://github.com/platform45/easy_roles.git


Step 2 : Generate migration to create column called roles in user's table

rails g easy_roles user roles
 

Step 3 : Run. rake db:migrate to run the migration
 
Step 4 : Add this line to the user's model
 
class User < ActiveRecord::Base
  easy_roles :roles
end


Add users role, remove, check role as follows.


@user = User.first 

@user.add_role 'admin' 

@user.is_admin? 
=> true 
   
@user.has_role? 'admin' 
=> true 
 
@user.is_awesome? 
=> false 
 
@user.add_role 'awesome' 
 
@user.is_awesome? 
=> true 
 
@user.remove_role 'admin' 
 
@user.is_admin? 
=> false 

Thursday, October 27, 2011

How to fix Unrecognized command line argument: 'package'

>> rvm package install zlib
ERROR: Unrecognized command line argument: 'package' ( see: 'rvm usage' )

The keyword 'package' is renamed to 'pkg'


Try,


>> rvm pkg install zlib


Njjoy :)

Tuesday, August 23, 2011

How to fix 'make' is not recognized as an internal or external command

Hi,
I have got this below error.
$ gem install rhodes-3.1.0.gem -l
Building native extensions.  This could take a while...
ERROR:  Error installing rhodes-3.1.0.gem:
        ERROR: Failed to build gem native extension.
c:/InstantRhodes/ruby/bin/ruby.exe extconf.rb
make
'make' is not recognized as an internal or external command,
operable program or batch file.
Gem files will remain installed in c:/InstantRhodes/ruby/lib/ruby/gems/1.8/gems/
rhodes-3.1.0 for inspection.
Results logged to c:/InstantRhodes/ruby/lib/ruby/gems/1.8/gems/rhodes-3.1.0/ext/
gem_make.out


Here is the Fix:
install Devkit for windows by following the steps,
https://github.com/oneclick/rubyinstaller/wiki/development-kit

--
Srikanth

Thursday, August 18, 2011

Rhodes + Blackberry + Fixing error + No such file or directory Simulator

 Hi,
I have got this error No such file or directory 'Simulator'
ltadmin@LT008029 ~/projects/SocialTango_Mobile (master)
$ rake run:bb
rake/rdoctask is deprecated.  Use rdoc/task instead (in RDoc 2.4.2+)
$use_sqlite : false
rake aborted!
No such file or directory - C:/bb/5.0.0.621_9650/simulator

This is how to Fix this,
Fix 1. Check if you have installed the Blackberry JDE. If you have installed Blackberry JDE there will be a simulator folder and MDS folder inside the installed directory. (In case if you have not installed JDE, here is where you need to download http://us.blackberry.com/developers/javaappdev/javadevenv.jsp)

Fix 2. If you have installed JDE and got the error. Go to Rhodes installation path and find the rhobuild.yml. In my system the path is,
C:\InstantRhodes\ruby\lib\ruby\gems\1.8\gems\rhodes-3.0.2\rhobuild.yml 
check if this paths are correct in rhobuild.yml:
    6.0:
      jde: C:/Program Files/Research In Motion/BlackBerry JDE 6.0
      mds: C:/Program Files/Research In Motion/BlackBerry JDE 6.0/MDS
      sim: 9800

Installing Rhodes, Running app in Blackberry Simulator in windows

1. Download the Instant Rhodes installer from http://docs.rhomobile.com/rhodes/install#install-on-windows and install it.  This will install Ruby, Rhodes.

 Note :  For this you will need to create account and login to the blackberry website.

3. Create a sample rhodes app. 

rhodes app myspace

4. Go to build.yml in the app, and change the version for blackberry,. 

bbver: 6.0
 
 
5. do 'rhodes-setup' for adding Java path  
$ rhodes-setup
We will ask you a few questions below about your dev environment.
JDK path (required) (C:/Program Files/Java/jdk1.6.0_21): C:/Program Files/Java/j
dk1.6.0_21

for other paths just skip. 

6. Go to Rhodes installation path and find the rhobuild.yml. In my system the path is,
C:\InstantRhodes\ruby\lib\ruby\gems\1.8\gems\rhodes-3.0.2\rhobuild.yml


add this lines in rhobuild.yml for blackberry version 6.0
    6.0:
      jde: C:/Program Files/Research In Motion/BlackBerry JDE 6.0
      mds: C:/Program Files/Research In Motion/BlackBerry JDE 6.0/MDS
      sim: 9800

7. Run the app., rake run:bb

This opens blackberry simulator. Now find your app in the apps menu.



Cheers!



Tuesday, August 16, 2011

Rhodes + Setup Android in windows + problems

Error 1 :

invalid command-line parameter: Files\Android\android-sdk\tools/emulator-arm.exe.
Hint: use '@foo' to launch a virtual device named 'foo'.
please use -help for more information

Fix: 
This problem is when you install Rhodes in the path "c:/Program Files/Android/android-sdk"  as there is a space in the word "Program Files". Try reinstalling to path "c:/Android/android-sdk"

Error 2 : 
sh.exe": /c/InstantRhodes/ruby/bin/rake: C:/RhoSync/ruby/bin/ruby.exe^M: bad interpreter: No such file or directory

Fix : reinstall the rake gem.

1. gem uninstall rake
2. gem install rake

This will update the rake Gem


Error 3 : Cannot find your Rhodes gem or source path.

 Fix :  run this in terminal. this will set up the rhodes path

$ set-rhodes-sdk
c:/InstantRhodes/ruby/lib/ruby/gems/1.8/gems/rhodes-3.0.2/bin






Wednesday, June 1, 2011

Rails - Calendar date select in 3 simple steps

1. Install plugin

script/plugin install http://calendardateselect.googlecode.com/svn/tags/calendar_date_select

2. Include JS & CSS to your layout file


    <link href="/stylesheets/calendar_date_select/blue.css" media="screen" rel="stylesheet" type="text/css" />

    <script src="/javascripts/calendar_date_select/calendar_date_select.js" type="text/javascript"></script>

3. Calendar date select tag

<input type="text" name="user[date_of_birth]" size="30" autocomplete="off" onselect="new CalendarDateSelect( this, {year_range:50} );" onclick="new CalendarDateSelect( this, {year_range:50} );" value="<%= Date.today %>"/>


Restart the server as the plugin has been installed! Calendar date select works!

Notes :
1. If you wish to turn on the time, use this => new CalendarDateSelect( this, {year_range:50, time:true} );

2. Adding (autocomplete="off") turns off the auto complete

Tuesday, May 24, 2011

Rails 3 - rake aborted! undefined method `task' for #

Hi,

In Rails 3. there was a problem with rake 0.9.0 gemset.

When i do rake db:create I got the following error,

undefined method `task' for #

The fix is as follows,

go to config/application.rb file.

Add this line inside the class,

include Rake::DSL


That fixed the problem

Wednesday, April 6, 2011

Helper method to display number in money format - number_with_delimiter

Examples

number_with_delimiter(12345678) # => 12,345,678
number_with_delimiter(12345678.05) # => 12,345,678.05
number_with_delimiter(12345678, :delimiter => ".") # => 12.345.678
number_with_delimiter(12345678, :separator => ",") # => 12,345,678
number_with_delimiter(12345678.05, :locale => :fr) # => 12 345 678,05
number_with_delimiter(98765432.98, :delimiter => " ", :separator => ",")

Source : http://apidock.com/rails/ActionView/Helpers/NumberHelper/number_with_delimiter

Learn :
Agile Web Development with Rails | Beginning Rails 3

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

Monday, January 24, 2011

Jquery Checkbox on click - enable/disable Items

I have used this code to enable/disable textboxes in the onclick of a Checkbox

$('#by_cheque').click(function() {
if ($('#by_cheque').is(':checked')) {
$('#payable_name').removeAttr('disabled');
} else {
$('#payable_name').attr('disabled', 'disabled');
}
});

Tuesday, January 11, 2011

cartographer - Google map API v3 plugin in rails

Hi all,

For using Google map v3, i always used with Javascript v3 provided by google. I didn't know there is an awesome plugin like this. anyways its not late.. Here is the GIT repo for it.

https://github.com/parolkar/cartographer

Also anyone knows more about Google map API plugins pls share ..

Thursday, January 6, 2011

Refresh Page with Javascript

Hi I have used the following JS for page refresh automatically.


function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}

<body onload="JavaScript:timedRefresh(120000);">

// 12000 - 2 minutes
// 100 - 1 second

Registering your App in Facebook

1. Register your APP here http://developers.facebook.com/setup , for local use your local URL ex). http://localhost:3000/
2. Click Submit, and once registered it will take you to a page.
3. In that click on Developer Dashboard.
4. Check if your Site URL.
5. Copy your App credentials to your App yml file.

fb_api_key: {your api key}
fb_secret: {your fb secret}
fb_app_id: {your app id}

Tuesday, January 4, 2011

A super simple Facebook Open Graph API client

For Facebook Graph API client. I checked a gem 'rest-graph'

Here is the git repo https://github.com/godfat/rest-graph

Authentication with Facebook, Twitter, etc

Hi,

I have came across this gem authlogic-connect.

https://github.com/viatropos/authlogic-connect

This provides Authentication with twitter, facebook, google, yahoo, myspace, vimeo, linked_in