Pages

Thursday 3 December 2015

URL encode in javascript while redirection

I got the problem while i set location.pathname in javascript. I set path with some parameters like

location.pathname = "/friendship/show_info?name="tarun"

Javascript encode my url and conver "?" to "%03" something

/friendship/show_info%03name="tarun"

So I use location.replace() instead of location.pathname which creates a prefect route.


Monday 30 November 2015

Scale Ruby on rails Applicaiton + ROR Books To Study + Test cases in rails

An Awesome blog On digitalocean scaling ROR applicaiton

https://www.digitalocean.com/community/tutorials/scaling-ruby-on-rails-setting-up-a-dedicated-mysql-server-part-2


Best ROR books to study

http://www.devbattles.com/en/sand/post-1317-10+RoR+Books+You+Must+Have+on+Your+Bookshelf


How to write test cases in rails

http://everydayrails.com/2012/03/19/testing-series-rspec-models-factory-girl.html


Free Bootstrap Templates

http://www.bootstrapzero.com/bootstrap-templates


Learn Algorithms and Data Structure

https://discuss.codechef.com/questions/48877/data-structures-and-algorithms

http://jeffe.cs.illinois.edu/teaching/algorithms/

https://class.coursera.org/algo-004/lecture


Learn Angular Basics

https://leanpub.com/recipes-with-angular-js/read


Free Online Web Chat Room

https://apprtc.appspot.com/

Wednesday 18 November 2015

Ruby On Rails Questions

Question

Rails:

Basic:
  1. What's new in rails 4?
  2. Difference b/w rails 3 and rails 4?
  3. Difference b/w rails 2 and rails 4?
  4. Where will you write the reusable code for controller in rails 4 ? (concerns)
  5. Where will you write the reusable code for model in rails 4 ? (concerns)
  6. What are gems in rails?
  7. What is difference b/w gems and plugins?
  8. What is difference b/w symbol and string?
  9. What is caching? What is russian doll caching?
  10. Why don't we use page caching and action caching. Also drawbacks for the same?
  11.  What is difference b/w string and symbol?
  12. Multiple inheritance in rails? And how can we use multiple inheritance in rails?
  13. Method Overloading in rails?
  14. Difference b/w include, extend and require?
  15. STI and Polymorphic associations?
  16. Different Examples for polymorphic association?
  17. About yield?
  18. Difference b/w class variables and instance variables?
  19. How will you get and set the values without using attr_accessible?
  20. How will you store foreign key to another column name?
  21. What is difference between include and join?
  22. Difference b/w proc and lambda?
  23. Practical use of proc and lambda?
  24. What is DRY principal?
  25. What are RESTful routes?
  26.  How many actions generated by scaffold command in rails 4?
  27. What in difference b/w put and patch?
  28. What is difference b/w get, put and post?
  29. How can you define constructor in rails?
  30. What is use of map in rails?
  31. Best tool for security measurement in rails?
  32. How everything in object in rails?
  33. What are dynamic finders?
  34. What is difference between session and cookies?
  35. Dynamic Methods in rails?
  36. What is use of bang (!) operator in rails?
  37. What is use of module?
  38. Is rails interpreted or compiled language?
  39. Which files load first environment.rb and application.rb ? Difference?
  40. Access modifier  in rails?
  41. Use of scope?
  42. What are sweepers and observers? Difference?
  43. Actions and method difference?
  44. What are filters?
  45. How render works? render is slow so how can we fast our rendering?
  46. What does request.xhr do?
  47. What is use js.erb file?
  48. Difference b/w render and redirect?
  49. How can we call third party service using ajax?
  50. What is Eager loading and lazy loading?
  51. What are validations? Give example?
  52.  What is use of helper method?
  53. Sql Injection and cross site forgery request?
  54. What is difference b/w render and redirect?
  55. What are different type of joins?
  56. What are turbolinks?
  57. String and symbol which is better to use? (string GC)
  58. What is garbage collector?
  59. What are callbacks? Types?
  60. How around_filter works?
  61. Create DB design for project timesheets?
  62. Use and How index works?
  63. Preference of columns for indexing?
  64. How capistrano works?
  65. if everything is an object in rails so how class keyword in an object?
  66.  Steps to increase page load speed?
  67. If we write redirect_to google.com in action ? will it come back to site? What will happen?
  68. Which loads first: layout's html file application.html.erb or action's html file like index.html.erb?
  69. If action is not available into the controller and html occurs for the action so will rails show error or not?
  70. How file loads? or hierarchy for loading the controller files?(alphabetically loads file)
  71. Use of config.ru?
  72. How routes call to particular action? An idea about routing?
  73. What are cron Jobs?
  74.  How to connect multiple databases?
  75. Can a model file connect to some other database in rails? How?
  76. Middleware in rails?
  77. What are alias in rails?
  78. How to create runtime methods?
  79. How to create singleton class? an example in rails? (logs)
  80. What are mixins?
  81. What are virtual attributes?
  82. What are whitelist/strong parameters?
  83. Why we use strong parameters in rails 4? Reason behind that?
  84. What is use of super?
  85. Why we use self? 
  86. Why not we use multiple inheritance and method overloading in rails?
  87. How many type of exceptions are in rails?
  88. How to enable you logging on production mode?
  89. Custom validations?
  90. Open classes?
  91. What are the use of initializers?
  92. Is internationalization occurs in rails?
  93. What is rake?
  94. Best practice to define constants?
  95. What are named scope in routing?
  96. What is use of concern in routing?
  97. What is use of transaction method in rails?
  98. What type of threading used in rails 4?
  99. Which javascript library use by default in rails 4?
  100. What is use of assets in rails ? 


OOPS :

Ques1: What is a class and object?
Ques2: How will you define a class (Real Time example) ?
Ques3: Why we need to create a class and why objects are created for a class ?
Ques4: What is use of class ?
Ques5: What is polymorphism, inheritance etc. Some basic oops concepts ?

Tuesday 17 November 2015

Difference b/w slim, haml and erb

As per the performance

Nice blog

https://sephinrothcn.wordpress.com/2014/04/14/slim-vs-haml-performance-perspective/

Monday 16 November 2015

Puma configuration with capistrano

config/deploy.rb

# config valid only for Capistrano 3.1
lock '3.3.5'

set :application, 'application'
set :repo_url, 'ssh url for gtihub-repo'

# Default branch is :master
# ask :branch, proc { `git rev-parse --abbrev-ref HEAD`.chomp }

set :rvm_type, :system
set :rvm_ruby_version, 'ruby-2.2.2'
# set :rbenv_type, :user # or :system, depends on your rbenv setup
# set :rbenv_ruby, '2.2.0'
# set :rbenv_prefix, "RBENV_ROOT=#{fetch(:rbenv_path)} RBENV_VERSION=#{fetch(:rbenv_ruby)} #{fetch(:rbenv_path)}/bin/rbenv exec"
# set :rbenv_map_bins, %w{rake gem bundle ruby rails}
# set :rbenv_roles, :all # default value

# Default deploy_to directory is /var/www/my_app
set :deploy_to, "/var/www/rails_apps/#{fetch(:application)}"
set :deploy_user, 'username'
set :use_sudo, false
set :password, ask('Server password:', nil, echo: false)
set :branch, ENV['REVISION'] || ENV['BRANCH_NAME'] || 'release2'

set :ssh_options, {
  forward_agent: true,
  # verbose: :debug,
  # user: fetch(:deploy_user),
  # password: fetch(:password)
}

# Default value for :scm is :git
set :scm, :git

set :bundle_binstubs, nil

# Default value for :format is :pretty
# set :format, :pretty

# Default value for :log_level is :debug
# set :log_level, :debug

# Default value for :pty is false
# set :pty, true

# Default value for :linked_files is []
set :linked_files, %w{config/database.yml}

# Default value for linked_dirs is []
set :linked_dirs, %w{log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/application}

# Default value for default_env is {}
# set :default_env, { path: "/opt/ruby/bin:$PATH" }

# Default value for keep_releases is 5
# set :keep_releases, 5
set :tmp_dir, "/home/username/tmp"

set :puma_rackup, -> { File.join(current_path, 'config.ru') }
set :puma_state, "#{shared_path}/tmp/pids/puma.state"
set :puma_pid, "#{shared_path}/tmp/pids/puma.pid"
set :puma_bind, "unix://#{shared_path}/tmp/sockets/puma.sock"    #accept array for multi-bind
set :puma_conf, "#{shared_path}/puma.rb"
set :puma_access_log, "#{shared_path}/log/puma_access.log"
set :puma_error_log, "#{shared_path}/log/puma_error.log"
set :puma_role, :app
set :puma_env, fetch(:rack_env, fetch(:rails_env, 'production'))
set :puma_threads, [0, 8]
set :puma_workers, 1
set :puma_worker_timeout, nil
set :puma_init_active_record, false
set :puma_preload_app, false
set :puma_prune_bundler, true
set :nginx_config_name, 'application'

# set :nginx_sites_available_path, "/usr/local/nginx/sites-available"
# set :nginx_sites_enabled_path, "/usr/local/nginx/sites-enabled"

namespace :deploy do

  after :restart, :clear_cache do
    on roles(:web), in: :groups, limit: 3, wait: 10 do
      # Here we can do anything such as:
      # within release_path do
      #   execute :rake, 'cache:clear'
      # end
    end
  end

end

config/deploy/production.rb

server 'server-address', user: 'username', roles: %w{web app db}
set :nginx_server_name, 'server-address'
set :rails_env, :production


Build gem from Scratch

$ bundle gem lorem
      create  lorem/Gemfile
      create  lorem/Rakefile
      create  lorem/.gitignore
      create  lorem/lorem.gemspec
      create  lorem/lib/lorem.rb
      create  lorem/lib/lorem/version.rb

Initializating git repo in /Users/eifion/code/ep245/lorem

The bundle gem command creates a new directory and generates several files in it. It also initializes a git repository there. This assumes that you’re using git and we’ll explain why it does this shortly. Before we do that we’ll walk you through some of the generated files, starting with the lorem.gemspec file.

/lorem/lorem.gemspec

# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "lorem/version"
 
Gem::Specification.new do |s|
  s.name        = "lorem"
  s.version     = Lorem::VERSION
  s.platform    = Gem::Platform::RUBY
  s.authors     = ["TODO: Write your name"]
  s.email       = ["TODO: Write your email address"]
  s.homepage    = ""
  s.summary     = %q{TODO: Write a gem summary}
  s.description = %q{TODO: Write a gem description}
 
  s.rubyforge_project = "lorem"
 
  s.files         = `git ls-files`.split("\n")
  s.test_files    = `git ls-files -- ↵
    {test,spec,features}/*`.split("\n")
  s.executables   = `git ls-files -- bin/*`.split("\n").map{ ↵
    |f| File.basename(f) }
  s.require_paths = ["lib"]
end

We can see straight away by looking at the TODO items that this file is designed to be edited directly. Once we complete these items we’ll have a working Gemspec file. One interesting part of this file are the file attributes towards the end of the file. Each of these is determined at runtime by using the git ls-files command by using git to determine the files that will be included in the gem and this is why bundle gem creates a git repository. The good thing about this is that it will automatically inherit the behaviour of the .gitignore file so that temporary files and the files we don’t want in our git repository (and therefore don’t want in our gem) are excluded. The defaults above will work for most gems but they can always be edited if we need different behaviour.

Another thing to note is how the version number is determined. This is defined as a constant called Lorem::VERSION and this value is defined in another file called version.rb in the lib/lorem directory. All this file does is define the version number.

/lib/lorem/version.rb
module Lorem
  VERSION = "0.0.1"
end
When it’s time to update our gem to a new version we can change the version number here and republish the gem.

The other file generated in the lib directory is called lorem.rb and it’s this file that’s loaded when someone requires our gem. We can put any code we like in this file or create other files in the lib directory and require them here. For our simple Lorem gem we’ll just create a class method called ipsum that returns some Lorem Ipsum text.

/lib/lorem.rb
module Lorem
  def self.ipsum
    "Lorem ipsum dolor sit amet, consectetur adipisicing ...."
  end
end
Publishing

So, we’ve finished our gem now and we’re ready to publish the first version. Before we do we’ll update the Gemspec file and replace the TODO text.

/lorem.gemspec
# -*- encoding: utf-8 -*-
$:.push File.expand_path("../lib", __FILE__)
require "lorem/version"
 
Gem::Specification.new do |s|
  s.name        = "lorem"
  s.version     = Lorem::VERSION
  s.platform    = Gem::Platform::RUBY
  s.authors     = ["Eifion Bedford"]
  s.email       = ["eifion@asciicasts.com"]
  s.homepage    = ""
  s.summary     = %q{Lorem ipsum generator}
  s.description = %q{Simply generates lorem ipsum text.}
 
  s.rubyforge_project = "lorem"
 
  s.files         = `git ls-files`.split("\n")
  s.test_files    = `git ls-files -- {test,spec,features}/*`.split("\n")
  s.executables   = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
  s.require_paths = ["lib"]
end
Then we can run the gem build command and point it to our Gemspec file.

$ gem build lorem.gemspec
WARNING:  no homepage specified
  Successfully built RubyGem
  Name: lorem
  Version: 0.0.1
  File: lorem-0.0.1.gem
This command generates a .gem file. If we were to run the gem push command now that would push the gem up to RubyGems.org and publish it so that others could install it.


Rails Deployment on Centos/Redhat

Centos
-------

$ yum -y update

Install the bundle containing development tools by executing the following command:

$ yum groupinstall -y 'development tools'

Some of the packages we need for this tutorial (e.g. libyaml-devel, nginx etc.) are not found within the official CentOS repository.

Run the following to add the EPEL repository:

$ sudo su -c 'rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm'

$ yum -y update

Finally, in order to install some additional libraries and tools, run the following command:

$ yum install -y curl-devel nano sqlite-devel libyaml-devel

$ curl -L get.rvm.io | bash -s stable

$ source ~/.profile
$ rvm reload

$ rvm requirements
(if got error "Requirements installation failed with status: 1")

$ rvm install 1.8.7

Close the connection and relogin to remove the error: RVM is not a funciton

$ rvm use 1.8.7-p374 --default

$ yum install git

---------------------------------------------------------------------------------------------

MySQL Install

To begin with, a simple MySQL install:


$ sudo yum install mysql-server mysql mysql-devel


Note that we have installed the development libs and headers with the 'mysql-devel' package. This package is required by the mysql Rubygems package which we install later in this article.
Start

We need to start the MySQL server to intiliaze the installation of the base MySQL databases.

$ sudo /etc/init.d/mysqld start

--------------------------------------------------------------------------------------------------------------


$ gem install passenger --no-ri --no-rdoc

$ yum install curl-devel httpd-devel 

The environment is now ready for the compilation. The process takes a few minutes and it’s started by the following command:

Unbale to restart the server

$ sudo chmod o+x "/home/user"

$ passenger-install-apache2-module  

$ ssh-keygen

$ cat id_rsa.pub >> ~/.ssh/authorized_keys

Note: once you've imported the public key, you can delete it from the server.

and finally set file permissions on the server:

$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys 

The above permissions are required if StrictModes is set to yes in /etc/ssh/sshd_config (the default).

Ensure the correct SELinux contexts are set:

$ restorecon -Rv ~/.ssh 

Now when you login to the server you won't be prompted for a password (unless you entered a passphrase when you created your key pair). By default, ssh will first try to authenticate using keys. If no keys are found or authentication fails, then ssh will fall back to conventional password authentication.

Once you've checked you can successfully login to the server using your public/private key pair, you can disable password authentication completely by adding the following setting to your /etc/ssh/sshd_config file:

# Disable password authentication forcing use of keys

PasswordAuthentication no

# Enter home directory
cd

#Give permissions

sudo chown -R user:user /path/to/direcrtory        #directory should be application deployment folder
sudo chmod -R g+w /path/to/directory


Create a new virtual host for your application.

Open the /etc/httpd/conf/httpd.conf file and uncomment the following line

NameVirtualHost *:80
At the end of the file, add

<VirtualHost *:80>
   ServerName yourdomain.com
   ServerAlias www.yourdomain.com
   DocumentRoot /home/newUser/my_rails_app/public
   <Directory /home/newUser/my_rails_app/public>
      AllowOverride all
      Options -MultiViews
   </Directory>
  ErrorLog /var/log/httpd/my_rails_app_error.log
  CustomLog /var/log/httpd/my_rails_app_access.log common
</VirtualHost>
Restart apache for the changes to take effect

sudo /etc/init.d/httpd restart

-----------------------------------------------------------------------------------------------------------------------------

Add Gem to your Gemfile
gem 'capistrano'

$ capify .

 Unable to start the Phusion Passenger watchdog because


Permission denied on rvm folder
chcon -R -h -t httpd_sys_script_exec_t /home/user/.rvm/

Getting error:
Starting httpd: Warning: DocumentRoot [/home/user/apps/alc/current/public] does not exist
Solution
 sudo setsebool -P httpd_enable_homedirs 1

 sudo visudo

nano /etc/httpd/conf/httpd.conf
add this conf on httpd.conf
ServerName 127.0.0.1


--------------------------------------------------------------------------------------------------------------------------


Set Up on REDHAT
----------------

yum -y update

Install the bundle containing development tools by executing the following command:

yum groupinstall -y 'development tools'

yum install gcc-c++ patch readline readline-devel zlib zlib-devel
yum install libyaml-devel libffi-devel openssl-devel make
yum install bzip2 autoconf automake libtool bison iconv-devel

gpg --keyserver hkp://keys.gnupg.net --recv-keys D39DC0E3  #if got error: GPG signature verification failed for

curl -L get.rvm.io | bash -s stable

source /etc/profile.d/rvm.sh


---------------------------------------------------------------------------------------------

MySQL Install

To begin with, a simple MySQL install:


sudo yum install mysql-server mysql mysql-devel


Note that we have installed the development libs and headers with the 'mysql-devel' package. This package is required by the mysql Rubygems package which we install later in this article.
Start

We need to start the MySQL server to intiliaze the installation of the base MySQL databases.

sudo /etc/init.d/mysqld start

yum install curl-devel httpd-devel



Understanding on Singleton

Code for singleton pattern

require "singleton"

class SimpleLogger
  include Singleton

  def initialize
    @output = []
  end

  attr_reader :output

  def error(message)
    output << formatted_message(message, "ERROR")
  end

  def info(message)
    output << formatted_message(message, "INFO")
  end

  def write(filename)
    File.open(filename, "a") { |f| f << output.join }
  end

  private

  def formatted_message(message, message_type)
    "#{Time.now} | #{message_type}: #{message}\n"
  end
end

Upgradation rails 2 to rails 4 (Errors)

Some Errors are given below while migration of rails 2 to rails 4
  • 'rake/rdoctask' is obsolete and no longer supported. Use 'rdoc/task' (available in RDoc 2.4.2+) instead.
require 'rake/rdoctask'
to
require 'rdoc/task'
  • undefined method `attr_accessible' for
Add ‘gem 'protected_attributes' to Gemfile
  • undefined method `link_to_function' for
Add patch in app/helpers/link_to_helper_function.rb

module LinkToFunctionHelper def link_to_function(name, *args, &block) html_options = args.extract_options!.symbolize_keys function = block_given? ? update_page(&block) : args[0] || '' onclick = "#{"#{html_options[:onclick]}; " if html_options[:onclick]}#{function}; return false;" href = html_options[:href] || '#' content_tag(:a, name, html_options.merge(:href => href, :onclick => onclick)) end end
  • ActiveRecord::AssociationNotFoundError (Association named 'authorizations' was not found on User
Change in lib/authenticated_system.rb:108 to (if using restful-authentication)


User.includes(:roles => :authorizations).find_by_id(session[:user_id])

  • undefined method `has_strings' for
Comment has_string wherever you find it.

  • Unknown key: :order. Valid keys are: :class_name, :class, :foreign_key…
Change format something like that


has_many :commission_reports, :order => "volume_year DESC, volume_month DESC", :dependent => :destroytohas_many :commission_reports, -> { order "volume_year DESC, volume_month DESC" }, dependent: :destroy
  • undefined method `on' for #<ActiveModel::Errors
Rails 4, the problem is that there's no "on" method for the Errors class anymore. We use "get". From

Change format something like that
@user.contact.errors.on(:attended_before)
 to
@user.contact.errors.get(:attended_before)
  • undefined method `call' when doing a simple query
Change scope from all models from

scope :enquiry, where({:involvement => INVOLVEMENT_ENQUIRY, :archived => false})
to
scope :enquiry, -> { where({:involvement => INVOLVEMENT_ENQUIRY, :archived => false}) }
  • Fix Typical Syntax on has_many like associations 
has_many :prices, -> { includes(:country).order("created_at desc") }, as: :priceable, dependent: :destroy, class_name: "Price"
  • Undefined method confirmed_me?
remove :confirmable from model where we have defined the devise parameters eg User model if not using
  • Unknown key: :include
Change has_many statement


  • NoMethodError (undefined method `authenticated?' )

FInd authenticated?  and replace with devise method valid_password?

  • NoMethodError (undefined method `forget_me' for
Copy forget_me method from restful-authentication to User model
  • link_to_function and the view helper with postfix _tag doesn’t work in rails 4 so the solution is
Add  Gem  into the gem file
gem 'prototype-rails'
In rails 2 prototype was supported but in rails 3 the jquery supports so we get the errors like
  • Keep in mind that the rails 2 already create a application.js and application.css in public folder so do not create same name files in assets folder. That can also give you conflicts.
  • element.dispatchEvent is not a function
Go to layout and check application layout


Here you have include the app/assets and public/assets together

So keep in mind the hierarchy of inclusion of files, in short
first jquery
second prototype
referred link
http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

<script src="prototype.js"></script>
<script src="jquery.js"></script>

After that include below in head of the html file the below line
<script>jQuery.noConflict();</script>
  • javascript_include_tag :default doesn’t work in rails 4
  • calendar_date_select doesn’t work in rails 4
  • LocalJump Error
This is due to the return keyword written in block. So remove return from the block.
  • undefined method `scoped' for
scoped method has been deprecated from rails 4. use all on place of it.
  • Search Or.. functionality was not working so change it that code
Replace div with some some id
  • Move all the assets from public folder to app folder



restful_authentication to Devise Migration


  • Add the following gem into your Gemfile
    • gem 'devise'
    • gem 'devise-encryptable'
  • Run the following commands from console
    • bundle intstall
    • rails g devise:install
  • In model file whatever you are using saving user information like user.rb
    • devise :database_authenticatable, :registerable, :recoverable, :rememberable, :confirmable, :validatable, :encryptable, :encryptor => :restful_authentication_sha1
          Modules :encryptable and :encryptor => :restful_authentication_sha1 are important here.
  • In config/initializers/devise.rb, configure as below
config.stretches = 1 config.pepper = ""

We are setting empty pepper and stretches to 1. This is how restful authentication works. It does not use stretches or pepper (by default).

( Note: You may find REST_AUTH_SITE_KEY in config/initializers/site_keys.rb )

In other case if You did set the REST_AUTH_SITE_KEY , then configure as below
config.stretches = 10
  config.pepper = "<YOUR_REST_AUTH_SITE_KEY>"

  • If you're using :validatable you may have to adjust your minimum password length. Devise uses 8, restful_authentication uses 6.
  • In config/initializers/devise.rb
                    config.password_length = 6..128

That is it for configuration. Now we have to change the table column names (without deleting them) to give devise what it wants. Here is the migration file I used. Change it according to your app's business logic.
  • Add migration to change columns
class ConvertRaToDevise < ActiveRecord::Migration
def self.up
  rename_column :users, "crypted_password", "encrypted_password"
 change_column :users, "encrypted_password", :string, :limit => 128, :default => "", :null => false
  rename_column :users, "salt", "password_salt"
  change_column :users, "password_salt", :string, :default => "", :null => false
  add_column :users, "remember_created_at", :datetime
end

def self.down
  remove_column :users, "remember_created_at"
  rename_column :users, "encrypted_password", "crypted_password"
  change_column :users, "crypted_password", :string, :limit => 40
  rename_column :users, "password_salt", "salt"
  change_column :users, "salt", :string, :limit => 40
end
end

You will able to use devise as authentication for your project.

Rails 2 to 4 UpGradation (Initial Level Settings)

Steps to upgrade the rails from 2 to 4 (Initial Level Settings)

  • Use latest ruby version first which is compatible with rails 4
  • Upgrade your Gems
    • Change versions for Gems into Gemfile .
    • Find alternative for gems which have been deprecated.
    • Comment some below gems if you have into you Gemfile
      • gem "mongrel"
      • gem "cgi_multipart_eof_fix" 
      • gem "fastercsv", '1.5.0'
      • gem “debugger"
    • Remove versions for these two basic Gems
      • gem 'mysql2'
      • gem 'rake'
  • Comment all the mime initializers in file config/initializers/mime_types.rb
  • Add config.egger_load in all rails environments in files config/environments/*
    • config.eager_load = true
  • Change match keyword from file routes.rb to get

You will able to run rails server from console

Wednesday 30 September 2015

About Me

About Me

My name is Tarun Garg, I’m 25 year old Software Engineer.  As I spend my work days working with an organisation. I have 4 years of relative experience in rails I live in Delhi, India. My total experience includes website development in ruby on rails. I also like to work as a freelancer for extra pays. 
I have in-depth knowledge and experience in requirement gathering, analysis, design, development, testing, API designs, AWS technologies and implementation of methodologies. I also offers experience in preparing standard documents such as program specification, design document, and training document. I am proficient in understanding business processes and requirements, and translating them into functional specifications. I have ability to build world class products using Agile/Scrum.
My responsibilities as Software developer includes client handling, better code optimizations, client satisfactions, understand requirements, better listener and give best to client. I assisted in the successful completion of some projects based on ROR. My clients also relied on my ability to skills such as code optimization, task completion, meet client requirements and excellent communications skills.

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>