Thursday, 29 January 2015

Bind Ports in UBUNTU

We always get the below errors on ubuntu machine in some cases

(98)Address already in use: AH00072: make_sock: could not bind to address [::]:80
(98)Address already in use: AH00072: make_sock: could not bind to address

I find the a command better than other commands to check binding of port 80 or some other port

$ sudo netstat -tulpn | grep :80

tcp        0      0  *       LISTEN      152/aolserver4-nsd

To kill the process

$ killall aolserver4-nsd

Now our port 80 is free to use

Log Rotation In Rails in Ubuntu

When we set up our application on server, we forget to rotate our logs.
What the rotate means here?
if your log size is increasing from some given value than the log will be replaced with a new empty file.
What is use of it?
If we do not rotate our logs, it takes a lot of memory and reach in GBs. It take a lot of useful space and server speed gets slow down after some time. It is junk and need to be clean after some time.
How we can do it?
There are two way to do so
one is set cron and second is there is a logrotate directory in linux so follow the below steps to rotate logs.

  1. In Linux, run the below command in terminal
        cd /etc/logrotate.d

  1. Create a new file, Write below command
        touch hc                    (hc is rails application name, it can be any name)

  1. Run the following commands and fill the file with below lines.
    sudo vi hc

    copy and paste the below lines

/home/likewise-open/ICPL/tarun.garg/apps/holidaycomparisons/log/*.log {
   rotate 3
   create 644 tarun.garg domain^users

/home/likewise-open/ICPL/tarun.garg/apps/holidaycomparisons/log/*.log  is path to my log directory

  1. 'rotate 3' signifies that only 3 logs of particular file.
  2. logfiles can be compressed using the gzip format by specifying 'compress' and 'delaycompress' delays the compression process till the next log rotation. 'delaycompress' will work only if 'compress' option is specified.
  3. 'missingok' avoids halting on any error and carries on with the next log file.
  4. 'notifempty' avoid log rotation if the logfile is empty.
  5. 'create <mode> <owner> <group>' creates a new empty file with the specified properties after log-rotation.
  6. Daily signifies that check the log daily.
  7. size signifies the size of the log after which it should be compressed.

Some ROR coding Standards

ROR Coding standards

Basic Stuff

 Two Spaces, No tabs

 Keep lines to a reasonable length(80 characters is classical but 100-120 is probably acceptable

with screen sizes these days)

 Method names should be intuitive and meaningful

 Variable names should be intuitive and meaningful

 Don’t commit commented out code - It makes everything confusing and it’s in the version

control anyway

 Comment when necessary - If comments are necessary check that your code couldn’t be

simplified first

 Maintain application style - If it’s a new application then be Railsy.

 If you want your application to survive then prioritize making the code easy to understand and


Code style

 Use UTF-8. It’s 21 century, 8bit encodings dead now.

 Use 2 space indent, not tabs

 Use Unix-style line endings

 Keep lines not longer than 80 chars

 Remove trailing whitespace

Development process

 Think

 Describe

 Write tests

 Implement & go green

 Rethink

 Refactor


 Follow MVC conventions

 Do not ever mix logics: no model/view logic in controller, no view logic in model & etc.

 Follow “Fat model, skinny controllers” methodology

 If you have different data representation, use format aliases (e.g. different html views for same

data: /users/:id.iphone)


 Keep it simple and clean

 Keep ApplicationController clean. Commonly it should be used only for global filters and per-

request logic (e.g locale configuration and access control)

 Keep in mind that all ApplicationController filters will be executed in each request and optimize

it to be ultra-fast

 Controllers should operate with abstract logic. Keep this logic simple and understandable

without detailed review. E.g:

# Disgusting

  Account.transaction do

    transfer = => :transfer, :receiver => @receiver, :ammount)


    if @sender.assets >= amount

      @sender.assets -= amount

      @receiver.assets += amount


      flash[:error] = "Balance not enough to transfer funds"

      success = false



    if! and! and!

      flash[:info] = "You have transferred #{ammount} to #{@receiver.last_name + "" +


      success = true


      errors = ...




  if !success

    respond_to ...


    respond_to ...


# Much better, but not quite abstract

  Account.transaction do

    @sender.withdraw amount

    @receiver.deposit amount


  if @sender.errors? or @receiver.errors?

    respond_to ...


    respond_to ...


# Best way

  if @sender.transfer!(amount, :to => @receiver)

    respond_to ...




 View interaction in controllers always should be placed in respond_to method or in responders

(for Rails 3)

 Do not place any logic in respond_to method

 Prefer :except in filters. E.g.: before_filter :authorize!, :except => [:index] to be sure that new

actions will be covered by filter by default

 Follow REST convention: Commonly one controller should only operate one resource.

 Follow REST convention naming. E.g.: UsersController should operate only users. Groups

operations should be placed in GroupsController

 Follow HTTP methods conventions in REST actions: DELETE for destructive action, PUT for

update, POST to create, GET to read

 Use nested resources when needed. E.g: map.resource :users {|user| user.resource :groups

}instead of groups action in UsersController

 Avoid deep nesting where it’s not necessary. E.g:

Not /places/:place_id/events/:event_id/usersbut /events/:event_id/users


 Keep it simple and clean

 Model, method and variable names should be obvious

 Do not use shortcuts and avoid non widely used abbreviation for model names. (e.g UsrHst or

UserHist should be UserHistory)

 Don’t repeat yourself

 Don’t repeat rails. Zero custom code that duplicates rails built-in functionality

 If you use find with similar condition in more than once — use named_scope

 If you use same code in more than one model turn it into module/library

 Prefer XML Builder over to_xml overrides



 Keep views simple

 Move complex logic to helpers

 Move HTML markup generation to helpers

 Do not use finders in views

 DRY. Use partials, but keep in mind that partials can be really slow

 Keep HTML markup semantic an clean

 Do not inline any Javascript code. It should be unobtrusive


 Follow Test Driven Development methodology: write tests, then code

 Keep tests simple and easy understandable

 Test everything what should be tested. If something can be broken: try to broke it by test

 Do not test rails built-in methods, test method usage

For more updates please fork on github

collection_check_boxes Rails Example

HTML code
<div style="width: 150px;height: 100px;overflow: scroll;">
 <%= check_box_tag "All" %>All<br/>   
 <%= f.collection_check_boxes  :category_ids, Category.all, :id, :category_name do |b| %>
    <%= b.check_box(class: "check_box")%>
    <%= b.label %>
 <% end %>
Javascript Code 
<script type="text/javascript">
    $('#All').click(function() {  
        if (this.checked) {
           $('.check_box').each(function() {
              this.checked = true;                       
        } else {
           $('.checkbox').each(function() {
              this.checked = false;                       

Google analyicts wth Rails

  1. Go to google analytics
  1. Sign Up in google analytics and fill the useful information. it will generate the javascript code. Copy that javascript code.
  2. Now paste that javascript code into the app/views/layouts/application.html.erb just up from the end of the body tag </body>.
    The given layout is the layout which I am using for all pages.

        javascript code provided by google analytics
 (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

 ga('create', 'UA-XXXX-XX', 'auto');
 ga('send', 'pageview');

  1. Most of the application are single page applications so it is necessary to keep track the ajax call also. so create a new file in app/assets/javascripts/ajax_pagetracker.js
Copy the below code into the file

(function ($) {
 $(document).ajaxSend(function(event, xhr, settings){
    if (typeof ga !== "undefined" && ga !== null) {
     ga('send', {
       'hitType': 'pageview',
       'page': settings.url


Note: Keep track the ajax calls via this method is not a better option at all because it will also track the other ajax calls like (loading the assets via ajax, loading the images via ajax). So keep track the images  and other calls  is not a better option at all. so we include tracking  code manually in every ajax. For ex.

     type : 'get',
     url : url,
     data : {"curr_code": currency}
         ga('send', {‘hitType': 'pageview', 'page':  url });
5. Include that file into the app/assets/javascripts/application.js. If you have used                      require_tree .   
than you don’t have need to include the file.
//= require ajax_pagetracker

6.  In rails 4, we also use turbolinks and google analytics doesn’t track the page loaded by the     turbolinks so follow the below steps for track the pages.

Create a new file in app/assets/javascripts/turbo_pagetracker.js

Paste the below code into the file.

$(document).on('page:change', function() {
 if (typeof ga !== "undefined" && ga !== null) {
    ga('send', {
     'hitType': 'pageview',
     'page': window.location.pathname

Also Include that file into app/assets/javascripts/application.js if require_tree is not available.

7. Now watch tracking of calls on the google analytics real time overview.

Friday, 17 October 2014

Set up Chef on Ubuntu Machine

Ubuntu + Chef + Errors

On  chef server(new ubuntu machine)

cd ~
Install the chef server or install from web site
=> wget

Install the package using terminal
=> sudo dpkg -i chef-server*

Run this command to confugre chef server on the machine
=> sudo chef-server-ctl reconfigure

Open browser (write https and ip of server)

Add default username and password.

On workstation(diiferent ubuntu machine)

update the system
=> sudo apt-get update

Install Git
=> sudo apt-get install git

Install Curl
=> sudo apt-get install curl

You can download the chef client from wesite and manually install this.
otherwise run
=> curl -L | sudo bash

Get the chef-repo from git
=> git clone

create .chef repository
=> mkdir ~/chef-repo/.chef

Copy the keys:

Now we will put the keys into .chef folder so open in browser put chef server url

Login and Tap on the Clients > edit(chef-validator) > chek the checkbox > save
It will generate a key so just copy the private key and paste in

create a chef-validator file in .chef folder
=> vim chef-validator.pem
paste the key

There should be no extra space
Now same for the Users > admin > edit > check checkbox  for regenerate the private key > save
It will generate a key so just copy the private key and paste in

create a chef-validator file in .chef folder
=> vim admin.pem
paste the key

run knife command
=> knife configure --initial

PASTE THE PATH ASKED BY OPETIONS LIKE FOR admin key path should be /home/vagrant/chef-repo/.chef/admnin.pem
same for the all

No need to commit the .chef folder so
=> vim ~/chef-repo/.gitignore

Add .chef in the end of the file


# Ignore Chef key files and secrets

run knife command to check if knife is configured or not
=> knife user list

if it gives error reconfigure the knife configuration

Client Node (another ubuntu instance) ip address(

now bootstrap to the clint using the following command
=> knife bootstrap -x username -P password -N name_for_node --sudo

If bootstraps success than you will find a node in chef-repo/nodes

Now chek client list
=> knife client list

Errors faced by me

While creating node
Error: RuntimeError: Please set EDITOR environment variable
export EDITOR=$(which vi)

ERROR: Failed to upload /home/vagrant/chef-repo/cookbooks/apt/recipes/default.rb
Chef-server redirects api clients between its components (in this case erchef and bookshelf). These redirects are based on the FQDN of the chef-server. If the server doesn't have a valid FQDN at install time, this can result in redirects to https://localhost:443.

One solution is to fix the FQDN on chef-server and run chef-server-ctl reconfigure.

Another solution is to set a few options in /etc/chef-server/chef-server.rb (I had to create this file) and then run chef-server-ctl reconfigure.

server_name = ""
api_fqdn server_name

nginx['url'] = "https://#{server_name}"
nginx['server_name'] = server_name
lb['fqdn'] = server_name
bookshelf['vip'] = server_name

Swap Memory in Ubuntu

Swap Memory + Ubuntu

I found these two blogs for swap memory which provide me a good understanding about swap memory and help me to increase swap memory of my Ubuntu system