Monday, 8 April 2019

Ruby On Rails Questions with Answers(List 1)

1. Getter and Setter in ruby?
    By using the attr_* form instead, we can get the existing value and set a new value.
    attr_accessor: for getter and setter both
    attr_reader: for getter only
    attr_writer: for setter on


2. What is Modules in Ruby?
   A Ruby module is an important part of the Ruby programming language. It’s a major object-oriented feature of the language and supports multiple inheritance indirectly.

    A module is a container for classes, methods, constants, or even other modules. Like a class, a module cannot be instantiated,
    but serves two main purposes:
    Namespace
    Mix-in

    Modules as Namespace
    A lot of languages like Java have the idea of the package structure, just to avoid collision between two classes. Let’s look into an example to understand how it works.
 
    module Patterns
      class Match
        attr_accessor :matched
      end
    end
    module Sports
      class Match
        attr_accessor :score
      end
    end
    match1 = Patterns::Match.new
    match1.matched = "true"
    match2 = Sports::Match.new
    match2.score = 210


    In the example above, as we have two classes named Match, we can differentiate between them and prevent collision by simply encapsulating them into different modules.

    Modules as Mix-in
    In the object-oriented paradigm, we have the concept of Interfaces. Mix-in provides a way to share code between multiple classes. Not only that, we can also include the built-in modules like Enumerable and make our task much easier. Let’s see an example.
 
  module PrintName
      attr_accessor :name
        def print_it
          puts "Name: #{@name}"
        end
    end


    class Person
    include PrintName
    end


    class Organization
    include PrintName
    end


    person = Person.new
    person.name = "Rajkumar"
    puts person.print_it # => Name: Rajkumar
    organization = Organization.new
    organization.name = "Rajkumar testing"
    puts organization.print_it # => Name: Rajkumar testing


    Mix-ins are extremely powerful, as we only write the code once and can then include them anywhere as required.

3. What Constructor and Destructor in ruby?
    A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor may also contain the group of instructions or a method which will execute at the time of object creation.
 
 # class name  
    class Demo 
       
        # constructor 
        def initialize   
            puts "Welcome to GeeksforGeeks!"  
        end  
     
    end   
     
    # Creating Obejct
    Demo.new
    output : Welcome to GeeksforGeeks!

    #Ruby program to initialize instance
    # class name
    class Geeks
         
        # constructor
        def initialize
             
            # instance variable intialzation
            @inst_1 = "GeeksforGeeks"
            @inst_2 = "Sudo Placement"
        end
         
        # display method
        def display
            puts "Value of First instance variable is: #{@inst_1}"
            puts "Value of Second instance variable is: #{@inst_2}"
        end
    end
     
    # creating object
    obj1 = Geeks.new()
     
    # calling display method
    obj1.display()
    Value of First instance variable is: GeeksforGeeks
    Value of Second instance variable is: Sudo Placement


    Destructor in ruby

    You can use ObjectSpace.define_finalizer when you create the image file, and it will get invoked when the garbage man comes to collect. Just be careful not to reference the object itself in your proc, otherwise it won't be collected by the garbage man. (Won't pick up something that's alive and kicking)
    class MyObject
      def generate_image
        image = ImageMagick.do_some_magick
        ObjectSpace.define_finalizer(self, proc { image.self_destruct! })
      end
    end

4. What is attr_accessor v/s attr_accesible  in ruby?

   attr_accessor is a Ruby method that makes a getter and a setter.
   attr_accessible is a Rails method that allows you to pass in values to a mass assignment: new(attrs) or update_attributes(attrs)
  
5. What is private v/s protected in ruby?
    protected methods can be called by any instance of the defining class or its subclasses.

    private methods can be called only from within the calling object. You cannot access another instance's private methods directly.

    class Test1
      def main_method
        method_private
      end

      private
      def method_private
        puts "Inside methodPrivate for #{self.class}"
      end
    end

    class Test2 < Test1
      def main_method
        method_private
      end
    end

    Test1.new.main_method
    Test2.new.main_method

    Inside methodPrivate for Test1
    Inside methodPrivate for Test2

    class Test3 < Test1
      def main_method
        self.method_private #We were trying to call a private method with an explicit receiver and if called in the same class with self would fail.
      end
    end

    Test1.new.main_method
    This will throw NoMethodError


    Protected method can be called with an implicit receiver, as like private. In addition protected method can also be called by an explicit receiver (only) if the receiver is "self" or "an object of the same class".

    class Test1
      def main_method
        method_protected
      end

      protected
      def method_protected
        puts "InSide method_protected for #{self.class}"
      end
    end

    class Test2 < Test1
      def main_method
        method_protected # called by implicit receiver
      end
    end

    class Test3 < Test1
      def main_method
        self.method_protected # called by explicit receiver "an object of the same class"
      end
    end


    InSide method_protected for Test1
    InSide method_protected for Test2
    InSide method_protected for Test3


    class Test4 < Test1
      def main_method
        Test2.new.method_protected # "Test2.new is the same type of object as self"
      end
    end

    Test4.new.main_method

    class Test5
      def main_method
        Test2.new.method_protected
      end
    end

    Test5.new.main_method
    This would fail as object Test5 is not subclass of Test1
    Consider Public methods with maximum visibility

Saturday, 16 March 2019

How to copy local files to remote server & remote server files to local system in ubuntu?

Copy local files to remote server(192.168.1.1)

 $ scp -r /home/rajkumar/Desktop/test ubuntu@192.168.1.1:/var/www/html/Projects/


Copy remote server(192.168.1.1) files to local system

$ scp -r username@domain:/var/www/html/Projects/test /home/rajkumar/Desktop 


 
 Copy local files to remote server(aws ec2)

$ scp -i "test.pem" /home/rajkumar/Desktop/rajkumar username@domainname:/var/www/html/Projects/


  Copy remote server(aws ec2) files to local system

$ scp -i "test.pem" -r username@domainname:/var/www/html/test/rajkumar /home/rajkumar/Desktop



Thursday, 14 March 2019

How to write RSpec for Rails model?

RSpec for model

1. Add the below gem in your Gemfile and run "bundle install"
    gem 'rspec-rails' 

2. To generate spec folder run the below command
    rails generate rspec:install

3. To generate spec for specific model run the below command
    rails g rspec:model Address

4. To write the spec test cases, add the below codes in "spec/address_spec.rb"
RSpec.describe Address, type: :model do
  it 'Belongs to Builder' do
    add = Address.new
    builder = Builder.new
    builder.addresses << add
    expect(add.builder).to be builder
  end
end


5. To run spec for all 
    bundle exec rspec

6. To run spec for specific model
    bundle exec rspec spec/models/address_spec.rb

7. To run spec with html format output.
    rspec spec/models/address_spec.rb --format h > output.html
 


Tuesday, 12 March 2019

How to get the hash key and value in ruby?


How to get the hash value using hash key in ruby

a = {1=>"Active", -1=>"Inactive", 0=>"Under Review"} 

a[1] # 'Active'

a[-1] # 'Inactive'

a[0] # 'Under Review'


How to get the hash key using hash value in ruby 


a = {1=>"Active", -1=>"Inactive", 0=>"Under Review"} 

a.key('Active') #1

a.key('Inactive') #-1

a.key('Under Review') #0

Thursday, 14 February 2019

Is there any function to get an array value from string except `eval`?


How to get an array value from string in ruby on rails without eval?

  

Input params in controller will be 
params[:city_id] = "1" or "[1,2,3,4,5]" 

Expected results should be [1] or [1,2,3,4,5] 

We can use eval(params[:city_id]).

Using eval method in controller is dangerous for sql. 

Result: 
 params[:city_id].scan(/\d+/).map(&:to_i)

Thursday, 31 January 2019

How to deploy rails application in ubuntu using apache & passenger

How to Deploy Rails application in ubuntu using Apache & passenger



1. Install the apache type the below command
   
   $ sudo sudo apt-get install apache2

2. Install passenger

   $ sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 561F9B9CAC40B2F7

3. Create an APT source file:
   
   $ sudo nano /etc/apt/sources.list.d/passenger.list
   
   insert this line inside passenger.list file

   deb https://oss-binaries.phusionpassenger.com/apt/passenger trusty main

   save and exit after inserting the above line.

4. Change the owner and permissions for this file to restrict access to root:

   $ sudo chown root: /etc/apt/sources.list.d/passenger.list
   $ sudo chmod 600 /etc/apt/sources.list.d/passenger.list   

5. Update the APT

   $ sudo apt-get update   

6. While updating if you face any issues. Kindly do the below things

   $ sudo rm -r /var/lib/apt/lists/*
   $ sudo apt-get clean
   $ sudo apt-get update

7. Install the passenger

   $ sudo apt-get install libapache2-mod-passenger

8. Enable and restart the server
   $ sudo a2enmod passenger
   $ sudo service apache2 restart      

9. After creating or pulling your application, Now we need to create a virtual host file for our project. We'll do this by copying the default Apache virtual host:   

   $ sudo cp /etc/apache2/sites-available/000-default.conf /etc/apache2/sites-available/serversetup.conf

10. Now open etc/apache2/sites-available/serversetup.conf file change the below things

    <VirtualHost *:80>
        ServerName localhost
        ServerAlias localhost

        ServerAdmin webmaster@localhost
        DocumentRoot /home/rajkumar/Rajkumar/Projects/serversetup/public
        RailsEnv production


        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        <Directory "/home/rajkumar/Rajkumar/Projects/serversetup/public">
            Options FollowSymLinks
            Require all granted
        </Directory>
    </VirtualHost>

 11. Disable the default site and enable new app.

    $ sudo a2dissite 000-default
    $ sudo service apache2 reload
    $ sudo a2ensite serversetup
    $ sudo service apache2 restart   

12. Now you check your ip address. Your application will work. Dont forget to do clean & precompile the app.

Monday, 28 January 2019

How to Deploy Rails Application using Nginx with Unicorn

Steps for Unicorn & Nginx Deployment in Rails

Unicorn Configuration

1. Add unicorn in gem file
gem 'unicorn'

2. Create new file in config folder
$ vim config/unicorn.rb

Paste the below codes in unicorn.rb file
# set path to application
app_dir = File.expand_path("../..", __FILE__)
shared_dir = "#{app_dir}/shared"
working_directory app_dir


# Set unicorn options
worker_processes 2
preload_app true
timeout 30

# Set up socket location
listen "#{shared_dir}/sockets/unicorn.sock", :backlog => 64

# Logging
stderr_path "#{shared_dir}/log/unicorn.stderr.log"
stdout_path "#{shared_dir}/log/unicorn.stdout.log"

# Set master PID location
pid "#{shared_dir}/pids/unicorn.pid"

3. Create the folder were referred in unicorn.rb files
$  mkdir -p shared/pids shared/sockets shared/log



Unicorn init script setup

1. Create init script file

$  sudo vim /etc/init.d/unicorn_serversetup

2. Paste the below script in unicorn_serversetup file

#!/bin/sh
### BEGIN INIT INFO
# Provides:          unicorn
# Required-Start:    $all
# Required-Stop:     $all
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: starts the unicorn app server
# Description:       starts unicorn using start-stop-daemon
### END INIT INFO

set -e

USAGE="Usage: $0 <start|stop|restart|upgrade|rotate|force-stop>"

# app settings
USER="rajkumar"
APP_NAME="/Rajkumar/Projects/serversetup"
APP_ROOT="/home/$USER/$APP_NAME"
ENV="production"

# environment settings
PATH="/home/$USER/.rbenv/shims:/home/$USER/.rbenv/bin:$PATH"
CMD="cd $APP_ROOT && bundle exec unicorn -c config/unicorn.rb -E $ENV -D"
PID="$APP_ROOT/shared/pids/unicorn.pid"
OLD_PID="$PID.oldbin"

# make sure the app exists
cd $APP_ROOT || exit 1

sig () {
  test -s "$PID" && kill -$1 `cat $PID`
}

oldsig () {
  test -s $OLD_PID && kill -$1 `cat $OLD_PID`
}

case $1 in
  start)
    sig 0 && echo >&2 "Already running" && exit 0
    echo "Starting $APP_NAME"
    su - $USER -c "$CMD"
    ;;
  stop)
    echo "Stopping $APP_NAME"
    sig QUIT && exit 0
    echo >&2 "Not running"
    ;;
  force-stop)
    echo "Force stopping $APP_NAME"
    sig TERM && exit 0
    echo >&2 "Not running"
    ;;
  restart|reload|upgrade)
    sig USR2 && echo "reloaded $APP_NAME" && exit 0
    echo >&2 "Couldn't reload, starting '$CMD' instead"
    $CMD
    ;;
  rotate)
    sig USR1 && echo rotated logs OK && exit 0
    echo >&2 "Couldn't rotate logs" && exit 1
    ;;
  *)
    echo >&2 $USAGE
    exit 1
    ;;
esac


3. Give user name and app name and save the files

4. Update the script's permissions and enable Unicorn to start on boot:

  $ sudo chmod 755 /etc/init.d/unicorn_serversetup
  $  sudo update-rc.d unicorn_serversetup defaults 

5. start the unicorn 

  $  sudo service unicorn_serversetup start

6. Your application will run shared/sockets/unicorn.sock 


Install and Configure Nginx

1. $ sudo apt-get install nginx

2. $ sudo vi /etc/nginx/sites-available/default

3. configure below items

upstream app {
    # Path to Unicorn SOCK file, as defined previously
    server unix:/home/deploy/appname/shared/sockets/unicorn.sock fail_timeout=0;
}

server {
    listen 80;
    server_name localhost;

    root /home/deploy/appname/public;

    try_files $uri/index.html $uri @app;

    location @app {
        proxy_pass http://app;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_redirect off;
    }

    error_page 500 502 503 504 /500.html;
    client_max_body_size 4G;
    keepalive_timeout 10;
}

4. $ sudo service nginx restart

5. Any 403 error you can check the sudo /var/log/nginx/error.log





Interactor in Rails

What is interactor? Interactor provides a common interface for performing complex user interactions An interactor is a simple, sin...