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