Friday, 5 July 2013

Rails4 , Faster loading with turbolinks

The Ruby on Rails version 4.0.0 has been just released. The team took one and half years for development, Rails 4 comes with some interesting new features such as  Turbolinks, improved caching and thread-safe.

Turbolinks changes your Rails application into a single page JavaScript application, that is, it doesn't load new pages but instead replaces the current page with new content from the server.

[ This is similar to pjax, but here we dont need to worry about which element on the page to replace, and combining the server-side response to add, The entire body will be replaced ]

Few major points on Turbolinks

1. Less Execution time : -
  1. Turbolinks makes following links in your web application faster. Turbolinks  won't allow the browser to recompile the JavaScript and CSS between each page change/loading, it keeps the current page there itself and replaces only the body and the title in the head.
  2. Execution time of code depends. The more CSS and JavaScript you have, the more benefit of not throwing away the browser instance and recompiling all of it for each and every page.
  3. In any case, the benefit can be up to two times faster in apps with lots of JS and CSS. Of course, your app's speed may vary, It'll be dependent on your browser version and all other factors affecting performance of your application.
2. No jQuery or any other framework : -

  1.   Turbolinks is built as light-weight.
  2.   It does not require jQuery or any other framework to work. But it works fine with jQuery or Prototype or whatever else like these frameworks.
3. Events :-
  1. Turbolinks changes the pages without a full page reload, so you can't rely on DOMContentLoaded or jQuery.ready() to trigger your code.
  2.  Instead Turbolinks triggers events on document to provide hooks into the lifecycle of the current page
4. Initialization
  1.   Turbolinks will be enabled whenever the server has rendered a GET request.
Eg :-
  • POST :create => resource successfully created => redirect to GET :show
    • Turbolinks ENABLED
  • POST :create => resource creation failed => render :new
    • Turbolinks DISABLED
5. Opting out of Turbolinks

  1. By default, Turbolinks is enabled for all internal HTML links. 
  2. You can opt out by marking links or their parent container with data-no-turbolink attribute
  3. After giving data-no-turbolink attr with in a div, then all links inside of that div will be treated as regular links.
Eg :- 
<a href="#">Home (via Turbolinks)</a>
<div data-no-turbolink>
  <a href="#">Home (without Turbolinks)</a>
6.  Visit links manually using turbolinks
You can use Turbolinks.visit(path) to go to a URL through Turbolinks.

Tuesday, 11 June 2013

Rails Kaminari - Ajax pagination

Here is a simple way to implement AJAX pagination using Kaminari gem.

Suppose, We are having a Product Model with fields id and name.

So, In the ProductsController,

def index
  @products =[:page]).per(params[:per])
   respond_to do |format|

in view file index.html.haml

    = render 'products'
    = paginate @products, :remote => true

And create _products.html.haml(this will be rendered from index) with content
    @products.each do |product|

Finally, We have to create one more  file _index.js.haml with content

$('#products').html("#{escape_javascript(render 'products')}");
$('#paginator').html("#{escape_javascript(paginate(@products, :remote => true)) }");

This post may help you. Please comment on the same, If you guys have any queries.

Monday, 21 January 2013

Jquery Auto Tab for Phone fields

Its a good thing, If  we implement autotab for telephone fields. It would be more nice. There are many Jquery plugins. But here I created my own simple autotab with a jquery function.

Here I'm explaining with rails application

Add onKeyup javascript event autotab() to your text fields in which you want to implement autotab

Then View should look like the following

<%=text_field_tag :isd, nil, :maxlength => 3, :onKeyup => "autotab(this)" %>
<%=text_field_tag :std, nil, :maxlength => 5, :onKeyup =>"autotab(this)"%>
<%=text_field_tag :num, nil, :maxlength => 12 %>

Then add the js function to your application.js

function autotab( field ){

This will do the autotab thing.
For any query please comment on the same thread. Thank you.

Monday, 7 January 2013

Rails mongoid has field model validation

This can be done only with a custom method validation, Such as
    class Comment
       include Mongoid::Document
       include Mongoid::Timestamps 
       include ActiveModel::Validations
       validate :must_be_friends
       def must_be_friends
         errors.add(:base, 'Must be friends to leave a comment') if hash[:firstname].nil?

Rails 3.2 Ajax Paperclip Image uploading

I was working on uploading images using paperclip gem . I wanted to use Ajax. I googled a lot, But every result says its not possible, that  you can't upload images using Ajax. Some Jquery plug-ins are available, But its not behaving like what I really needed in my project.

Finally I got the solution for this problem. It is a common solution. First of all download the the js code and save it as jquey.form.js in assets/javascripts. Include in application.js like

    //= require jquery.form

Next is your view. Which may look like this

    <div id="image_view">
      <%=image_tag @model.image_attr_name.url %>

Next is your form to upload image
[You can use bootstrap modal to render this form. Then it'll be more beautiful]

    <%=form_for @model, :html => { :multipart => true, :id => "form_id" }, :url => url_for(:controller => 'controller', :action => 'method') do | f | %>
     Upload picture : <%= f.file_field image_attr_name %>
     <%= f.submit "Save changes", :id => :upload_pic %>
    <% end %>

Then add some javascript to the file where the form is rendered

    <script type="text/javascript">
        $('#upload_pic').click(function() {
          $("#form_id").ajaxForm({ target: "#image_view" }).submit(); // This line will display the ajax response in "image_view" div.
          //$("#modal_id").modal('hide'); if using modal uncomment this line to close current modal
          return false;

Then write the method in corresponding controller

    def method
      @pic = params[:model_name] )    
      render :template => "corresponding_view_file(ie, like pictures/show)", :layout => false

Note : You can use this method for submitting forms which handle fields of any data types. So if you guys have more fields, you can simply add those in the form and view file. Ajax will remain same.

Hope You people know how the model and Gemfile look like. I think It may help you. For any query please comment on the same thread. Thank you.