DataTables : Customizing navigation button

var $workflowTable = $('.workflow-table');
  $workflowTable.dataTable(
    {
      'iDisplayLength': 10,
      'fnDrawCallback': function (oSettings) {
        if (oSettings._iDisplayLength > oSettings.fnRecordsDisplay()) {
          $(oSettings.nTableWrapper).find('.dataTables_paginate').hide();
        }
        var curPage = Math.ceil(oSettings._iDisplayStart / oSettings._iDisplayLength) + 1;
        var lastPage = Math.ceil( oSettings.fnRecordsDisplay() / oSettings._iDisplayLength );

        if (curPage === 1){
          $(oSettings.nTableWrapper).find('.paginate_disabled_previous').hide();
        }else{
          $(oSettings.nTableWrapper).find('.paginate_enabled_previous').show();
        }
        if(curPage === lastPage){
          $(oSettings.nTableWrapper).find('.paginate_disabled_next').hide();
        }else{
          $(oSettings.nTableWrapper).find('.paginate_enabled_next').show();
        }
      }
    }
  );

jQuery Plugin : Full Calender Plugin : Delete button on Hover in Events

// iN 'eventAfterAllRender' Callback of full calender
,
eventAfterAllRender: function(view){
  addDeleteButtonOnEvents();
  customizeEventForPupup();
},
function addDeleteButtonOnEvents() {
  var $fcEvent = $(document).find('.fc-event');
  $fcEvent.each(function () {
    var $fcEvent = $(this);
    var splittedHREF = $fcEvent.attr('href').split('/');

    // GET SECOND LAST ITEM FROM ARRAY
    var eventId = splittedHREF.slice(-2, -1)[0];

    $(this).find('.fc-event-inner').append(
    '<div id="fc-event-delete-button-' + eventId + '" title="Delete" rel="tooltip" class="fc-event-delete-button"></div>'
    );
  });

  // Assign fancy tooltip to delete button recently added to the  DOM
  $(document).find('.fc-event-delete-button').tooltip();
}
.fc-event{
  &:hover .fc-event-delete-button{
      display: block;
  }
  .fc-event-delete-button{
    display: none;
    background: url(asset-path('icon-delete1.png')) no-repeat 0 0;
    width: 14px;
    height: 17px;
    margin: 0 0 0 10px;
    position: absolute;
    right: 8px;
    top: 2px;
  }
  .fc-event-time {
    display: none;
  }

  .fc-event-title{
    text-align: center;
  }
}

Install gem ‘Rake ‘ in windows

The reason is old rubygems. So we need to remove ssl source to be able to update gem --system which includes rubygems and so on. after this we can feel free to get back to ssl source.
gem sources -r https://rubygems.org/ - to temporarily remove secure connection
gem sources -a http://rubygems.org/ - add insecure connection
gem update --system - now we're able to update rubygems without SSL
after updating rubygems do vice versa
gem sources -r http://rubygems.org/ - to remove insecure connection
gem sources -a https://rubygems.org/ - add secure connection
Now you're able to update gems using secure connection.
gem update

Difference between Ruby’s Load, Include, Require and Extend

When you Include a module into your class as shown below, it’s as if you took the code defined within the module and inserted it within the class, where you ‘include’ it. It allows the ‘mixin’ behavior. It’s used to DRY up your code to avoid duplication, for instance, if there were multiple classes that would need the same code within the module.

The following assumes that the module Log and class TestClass are defined in the same .rb file. If they were in separate files, then ‘load’ or ‘require’ must be used to let the class know about the module you’ve defined.

module Log
  def class_type
    "This class is of type: #{self.class}"
  end
end
class TestClass
  include Log
  # ...
end
tc = TestClass.new.class_type
puts tc

The above will print “This class is of type: TestClass”

The load method is almost like the require method except it doesn’t keep track of whether or not that library has been loaded. So it’s possible to load a library multiple times and also when using the load method you must specify the “.rb” extension of the library file name.

Most of the time, you’ll want to use require instead of load but load is there if you want a library to be loaded each time load is called. For example, if your module changes its state frequently, you may want to use load to pick up those changes within classes loaded from.

Here’s an example of how to use load. Place the load method at the very top of your “.rb” file. Also the load method takes a path to the file as an argument:

load 'test_library.rb'

So for example, if the module is defined in a separate .rb file than it’s used, then you can use the

File: log.rb

module Log
  def class_type
    "This class is of type: #{self.class}"
  end
end

File: test.rb

load 'log.rb'
class TestClass
  include Log
  # ...
end

The require method allows you to load a library and prevents it from being loaded more than once. The require method will return ‘false’ if you try to load the same library after the first time. The require method only needs to be used if library you are loading is defined in a separate file, which is usually the case.

So it keeps track of whether that library was already loaded or not. You also don’t need to specify the “.rb” extension of the library file name.

Here’s an example of how to use require. Place the require method at the very top of your “.rb” file:

require 'test_library'

When using the extend method instead of include, you are adding the module’s methods as class methods instead of as instance methods.

Here is an example of how to use the extend method:

module Log
  def class_type
    "This class is of type: #{self.class}"
  end
end
class TestClass
  extend Log
  # ...
end
tc = TestClass.class_type
puts tc

The above will print “This class is of type: TestClass”

When using extend instead of include within the class, if you try to instantiate TestClass and call method class_type on it, as you did in the Include example above, you’ll get a NoMethodError. So, again, the module’s methods become available as class methods.

has_and_belongs_to_many association: Rails

The has_and_belongs_to_many Association

A has_and_belongs_to_many association creates a direct many-to-many connection with another model, with no intervening model. For example, if your application includes assemblies and parts, with each assembly having many parts and each part appearing in many assemblies, you could declare the models this way:

class Assembly < ActiveRecord::Base
  has_and_belongs_to_many :parts
end
class Part < ActiveRecord::Base
  has_and_belongs_to_many :assemblies
end

has_and_belongs_to_many Association Diagram

The corresponding migration might look like this:

class CreateAssembliesAndParts < ActiveRecord::Migration
  def change
    create_table :assemblies do |t|
      t.string :name
      t.timestamps null: false
    end
    create_table :parts do |t|
      t.string :part_number
      t.timestamps null: false
    end
    create_table :assemblies_parts, id: false do |t|
      t.belongs_to :assembly, index: true
      t.belongs_to :part, index: true
    end
  end
end

Source : http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

Chart.JS : JQuery Canvas Chart plugin: ZoomOut and reDrawing (IMage resolution) issue

/**
 * Renders the charts in specified Divs
 * @param data
 * @param idOfCanvas
 */
function renderPie(data, idOfCanvas) {
    var $canvas = $('#' + idOfCanvas);
    var $parent = $canvas.parent(); 
    /** 
    *   Canvas needs to be removed and re-rendered before we draw the chart
    *   Reason: When Chart is rendered and Window is Zoomed Out, On hovering the chart produces
    *   glitch in the chart
    */
    $canvas.remove();
    $parent.prepend("<canvas width='" + WIDTH_OF_PIE + "' height='" + HEIGHT_OF_PIE + "' id='" + idOfCanvas + "'>");
    
    var ctx = $parent.find('#' + idOfCanvas).get(0).getContext("2d");
    var chart = new Chart(ctx).Pie(data, {
        maintainAspectRatio: true,
        responsive: false,
        // String - Template string for single tooltips
        tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
        //String - A legend template
        legendTemplate: "<ul class=\"<%=name.toLowerCase()%>-legend\"><% for (var i=0; i<segments.length; i++){%><li><span style=\"background-color:<%=segments[i].fillColor%>\"></span><%if(segments[i].label){%><%=segments[i].label%> <strong><%=segments[i].value%></strong><%}%></li><%}%></ul>"

    });
    var legend = chart.generateLegend();
    $('#' + idOfCanvas + '-legend').html(legend);
}

yes it works, I have tested
I my case, I have a ‘select’ with list of locations. With each location data reloads in pie.
Issue ( Only when window is Zoomed Out) : With each reload the width and height of the canvas decreased continuously. Ultimately after 4 to 5 reloads the pie almost vanishes.
Solution: Before every reload, delete the previous canvas so that the older canvas along with its values is deleted.

responsive:true is not the solution, irrespective of responsive:true the chart’s size goes on decreasing for -ve zoom and increases for +ve zoom : Condition: The Window’s zoom must not be 100%

Rails : Layout and rendering :: Gist/Theme

2 Creating Responses

From the controller’s point of view, there are three ways to create an HTTP response:

  • Call render to create a full response to send back to the browser
  • Call redirect_to to send an HTTP redirect status code to the browser
  • Call head to create a response consisting solely of HTTP headers to send back to the browser

    2.1 Rendering by Default: Convention Over Configuration in Action

    if you have this code in your BooksController class:

    class BooksController < ApplicationController
    end

    And the following in your routes file:

    resources :books

    And you have a view file app/views/books/index.html.erb:

    <h1>Books are coming soon!</h1>

    Rails will automatically render app/views/books/index.html.erb when you navigate to /books and you will see “Books are coming soon!” on your screen.

  • The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the action_name.html.erb template in the controller’s view path and render it. So in this case, Rails will render the app/views/books/index.html.erb file
    2.2.1 Rendering Nothing

    Perhaps the simplest thing you can do with render is to render nothing at all:

    render nothing: true
    or
    head :bad_request
    2.2.2 Rendering an Action’s View

    If you want to render the view that corresponds to a different template within the same controller, you can use render with the name of the view:

    def update
      @book = Book.find(params[:id])
      if @book.update(book_params)
        redirect_to(@book)
      else
        render "edit"
       # render :edit you can rather use symbol
      end
    end

    If the call to update fails, calling the update action in this controller will render the edit.html.erbtemplate belonging to the same controller.

    2.2.3 Rendering an Action’s Template from Another Controller
    you can render the results of an action to a template in app/views/products this way:
    render "products/show"

    you can use the :template option (which was required on Rails 2.2 and earlier):

    render template: "products/show"
    2.2.4 Rendering an Arbitrary File
    render "/u/apps/warehouse_app/current/app/views/products/show"
    or
    render file: "/u/apps/warehouse_app/current/app/views/products/show"
    2.2.7 Rendering Text

    You can send plain text – with no markup at all – back to the browser by using the :plain option to render:

    render plain: "OK"

    Rendering pure text is most useful when you’re responding to Ajax or web service requests that are expecting something other than proper HTML.

    2.2.9 Rendering JSON

    JSON is a JavaScript data format used by many Ajax libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:

    render json: @product
    2.2.10 Rendering XML

    Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:

    render xml: @product
    2.2.11 Rendering Vanilla JavaScript

    Rails can render vanilla JavaScript:

    render js: "alert('Hello Rails');"

    This will send the supplied string to the browser with a MIME type of text/javascript.

    2.2.13 Options for render

    Calls to the render method generally accept four options:

    • :content_type
    • :layout
    • :location
    • :status

2.2.13.1 The :content_type Option

render file: filename, content_type: "application/rss"
By default, Rails will serve the results of a rendering operation with the MIME content-type of text/html (or application/json if you use the :json option)
2.2.13.2 The :layout Option
You can use the :layout option to tell Rails to use a specific file as the layout for the current action:
render layout: "special_layout"

You can also tell Rails to render with no layout at all:

render layout: false
2.2.13.3 The :location Option

You can use the :location option to set the HTTP Location header:

render xml: photo, location: photo_url(photo)
2.2.13.4 The :status Option

Rails will automatically generate a response with the correct HTTP status code (in most cases, this is 200 OK). You can use the :status option to change this:

render status: 500
render status: :forbidden

To include app/assets/stylesheets/main.css and app/assets/stylesheets/columns.css:

<%= stylesheet_link_tag "main", "columns" %>

To include app/assets/stylesheets/main.css and app/assets/stylesheets/photos/columns.css:

<%= stylesheet_link_tag "main", "photos/columns" %>

To include http://example.com/main.css:

<%= stylesheet_link_tag "http://example.com/main.css" %>

Rails application:: Assets not precompiling

In rails, you may some time have problem of  JS or CSS not being up-to-date. This problem may occur due various reasons:

  • It may occur due to caching by browser: To solve this press CTRL + SHIFT + R button in browser
  • It may occur due to assets caching by Rails server: To solve this type following command in terminal.      [You must be inside the rails app directory in terminal]
rake tmp:cache:clear
rake assets:precompile

# To ensure it works properly, please restart the server once

Installation Guide: Ruby On Rails: Ubuntu 14.04

Installing Ruby


RVM is the best Tool to manage multiple versions in your system.

# Update your package manager first:

$ sudo apt-get update
# Install dependencies for ruby
# This installs CURL, Git and other dependencies

sudo apt-get install git-core curl zlib1g-dev build-essential libssl-dev libreadline-dev libyaml-dev libsqlite3-dev sqlite3 libxml2-dev libxslt1-dev libcurl4-openssl-dev python-software-properties
sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
# To get the signature
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3

if it fails:

 command curl -sSL https://rvm.io/mpapis.asc | gpg --import -
curl -L https://get.rvm.io | bash -s stable
For all in one installation append --rails or --ruby or --ruby=1.9.3
Note: RVM might not be available right after installation is complete. Restart the terminal once after installation is completed.
#[ rvm install ruby ] installs latest version of ruby
rvm install 2.1.2
rvm use 2.1.2 --default

# Check the version of ruby installed
ruby -v
git config --global color.ui true
git config --global user.name "YOUR NAME"
git config --global user.email "YOUR@EMAIL.com"

# Create SSH Key
ssh-keygen -t rsa -C "YOUR@EMAIL.com"

# Now you need to add this public key to your github account
# You need to copy and paste the content of ~/.ssh/id_rsa.pub file to https://github.com/settings/ssh
# after clicking Add SSH Key buttton
# Once you have done this, you have to type following command to check
# if it worked

ssh -T git@github.com
# Hopefully, you will get this echoed

"Hi excid3! You've successfully authenticated, but GitHub does not provide shell access."

We need to install javascript runtime like NodeJS. This will let you use CoffeeScript and Gems you use to minify your javascripts (such as uglifier).

To install NodeJS, we need to add it using a PPA repository:

sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
gem install rails
# Check the version of rails installed

rails -v
# Rails 4.1.6
sudo apt-get install mysql-server mysql-client libmysqlclient-dev

Installing the libmysqlclient-dev gives you the necessary files to compile the mysql2 gem which is what Rails will use to connect to MySQL when you setup your Rails app.