Pages

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 0.0.0.0:80


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

command
$ sudo netstat -tulpn | grep :80

Result:
tcp        0      0 127.0.0.1:80            0.0.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 {
   size=20M
   daily
   rotate 3
   compress
   delaycompress
   missingok
   notifempty
   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

navigate.

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

MVC


 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)

Controllers


 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 = @sender.orders.new(:action => :transfer, :receiver => @receiver, :ammount)

   

    if @sender.assets >= amount

      @sender.assets -= amount

      @receiver.assets += amount

    else

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

      success = false

    end

   

    if @sender.save! and @receiver.save! and transfer.save!

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

@receiver.first_name}"

      success = true

    else

      errors = ...

    end

  end

 

  if !success

    respond_to ...

  else

    respond_to ...

  end

# Much better, but not quite abstract


  Account.transaction do

    @sender.withdraw amount

    @receiver.deposit amount

  end

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

    respond_to ...

  else

    respond_to ...

  end

# Best way

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

    respond_to ...

  else

    respond_to

  end

 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

Models


 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

Views

 Views is for presentation. DO NOT EVER CHANGE STATE OF ANYTHING IN VIEW

 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

Tests

 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

https://github.com/tarungarg/rails-style-guide

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| %>
    <span>
    <%= b.check_box(class: "check_box")%>
    <%= b.label %>
    </span>
 <% end %>
</div>
Javascript Code 
<script type="text/javascript">
  $(document).ready(function(){
    $('#All').click(function() {  
        if (this.checked) {
           $('.check_box').each(function() {
              this.checked = true;                       
           });
        } else {
           $('.checkbox').each(function() {
              this.checked = false;                       
           });
        }  
     });
   });
</script>

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
 
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
 (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
 m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
 })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

 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
     });
    }
 });

})(jQuery);

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.

    $.ajax({
     type : 'get',
     url : url,
     data : {"curr_code": currency}
    }).done(function(){
         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.