Sunday, December 30, 2012

Using requirejs with backbonejs (Rails)

So, after fighting with it for hours, finally I got it working so I thought it might help someone. I will got through step by step

1 - Create a new Rails application and set it up so that it loads an empty index page
     (Create a controller with an index action + add an index view + edit the routes file accordingly)

2 - Add the following line to the Gemfile - gem 'requirejs-rails'


3 - In application.html.erb file, replace
     <%= javascript_include_tag "application" %> with <%= requirejs_include_tag "application" %>


4 - Add a requirejs.yml file under config directory and delete all the content of application.js

5 - In the vendor/assets/javascripts directory, add backbone.js, underscore.js and JQuery libraries

6 - Add the code as shown below to the corresponding files
   
    
-----------------------------------------------
application.js
-----------------------------------------------
require [
'backbone',
'path/to/router/with/index/handler'],
(Backbone, IndexRouter) ->
$ ->
Main = new IndexRouter()
Backbone.history.start()
-----------------------------------------------
requirejs.yml
-----------------------------------------------
modules:
- name: 'application'
shim: {
'backbone': {
# These script dependencies should be loaded before loading
# backbone.js
deps: ['underscore', 'jquery'],
# Once loaded, use the global 'Backbone' as the
# module value.
exports: 'Backbone'
}
}
------------------------------------------------
MainRouter.js
------------------------------------------------
define [
'backbone'],
(Backbone, $) ->
class IndexRouter extends Backbone.Router
routes:
'': 'index'
index: () ->
alert("wooo..It works")


7 - Credit goes to - https://github.com/jwhitley/requirejs-rails

8 - Thanks

Saturday, September 1, 2012

Rails like flash messages using JQuery for JS or AJAX calls

# This gist shows how to display Rails like flash messages while handling AJAX or JS requests
# Note - This might not be the best way to do this but it works for me
Step 1. Create a partial which will contain the message to be displayed
Example - _success.html.erb
<div id="flash_message">
<p>Success</p>
</div>
Step 2. In the Controller, add code to call this partial on a JS request
Example - ExampleController.rb
class ExampleController < ApplicationController
.
.
.
def example_action
.
.
respond_to |format|
# This call will search for action success, if not present, it will call the template named success.js
# Note - success.js is created in step 3
format.js { render :action => 'success' if some_condition }
end
end
end
Step 3. Create a file called success.js which will render the flash message
Example - success.js.erb
$("#element_where_flash_to_appear").prepend(
$("<%= escape_javascript(render :partial => 'success') %>").
hide().fadeIn(1000, function(){
$(this).remove();
})
);
Step 4. CSS for flash message
#flash_message {
text-align: center;
background: #ffe;
width:100%;
margin-left:auto;
margin-right:auto;
border:1px solid gray;
margin:0px;
}

Thursday, August 2, 2012

Fibonacci in log(n) Java code

/*
* | 1 1 |n |Fn+1 Fn |
* | 1 0 | = |Fn Fn-1 |
*
* Figure 1
*/
public int FibonacciLogN(int n)
{
if(n <= 0)
return 0;
if(n == 1 || n == 2)
return 1;
// calculate n - 1 term (see above figure 1)
return FibonacciMatrix(FIBONACCI_MATRIX, n - 1)[0][0];
}
private int[][] FibonacciMatrix(int[][] m, int n)
{
if(n == 1)
return FIBONACCI_MATRIX;
if(n == 2)
return multiply(FIBONACCI_MATRIX, FIBONACCI_MATRIX);
int solution[][] = FibonacciMatrix(m, n/2);
solution = multiply(solution, solution);
if(n%2 != 0)
solution = multiply(solution, FIBONACCI_MATRIX);
return solution;
}
// for quick multiplication
private int[][] multiply(int[][] m, int[][] n)
{
int[][] result = new int[2][2];
result[0][0] = m[0][0] * n[0][0] + m[0][1] * n[1][0];
result[0][1] = m[0][0] * n[0][1] + m[0][1] * n[1][1];
result[1][0] = m[1][0] * n[0][0] + m[1][1] * n[1][0];
result[1][1] = m[1][0] * n[0][1] + m[1][1] * n[1][1];
return result;
}
private int[][] FIBONACCI_MATRIX = new int[][] { {1,1}, {1,0} };

Wednesday, June 20, 2012

Posting code to Blogger using - GitHub Gists :)

1. Add a gist to your git hub account
2. Get the embed link by clicking on the embed button or show embed. (See next line )
    Embed All Files: show embed
3. Copy the script and paste it in your blog
4. Enable "Interpret typed HTML" under Post settings -->Options -->Interpret typed HTML
5. And wallah !!

Ruby on Rails - Downloading data as xls or excel without using a Gem

# This gist demonstrates - How to download data from database in excel or xls format in Ruby on Rails
# Tested with - Ruby 1.9.3, rails 3.2.1, db - postgres
class DownloadsController < ApplicationController
before_filter :define_header, :except => :index
def index
...
end
def download_choclates
@choclates = Choclate.all
respond_to do |format|
format.html { render :partial => 'download_choclates' }
end
end
private
# sets the header. You can specify the file name
# For my project I am sending the name of the file in params
# so I use
# headers['Content-Disposition'] = "attachment; filename=#{params[:name]}.xls"
def define_header
headers['Content-Type'] = "application/vnd.ms-excel"
headers['Content-Disposition'] = "attachment; filename=filename.xls"
headers['Cache-Control'] = ''
end
end
# Partial to be rendered
# _download_choclates.html.erb
<table border="1">
<tr>
<th>Id</th>
<th>Description</th>
<th>Price</th>
<th>Feedback</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
<% @choclates.each do |choclate| %>
<tr>
<td><%= choclate.id %></td>
<td><%= choclate.description %></td>
<td><%= choclate.price %></td>
<td><%= choclate.feedback %></td>
<td><%= choclate.created_at %></td>
<td><%= choclate.updated_at %></td>
</tr>
<% end %>
</table>
view raw download_xls.rb hosted with ❤ by GitHub

Awesome !! Thanks Google

A free blog ... with the name of my choice ... no maintenance cost ... nothing ...