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





Monday, 31 December 2018

Export and Import options for Mysql & Postgresql Databases

DataBase Dump & Restore for MYSQL
 
Take dump from database or Export from database

   Terminal : mysqldump -h localhost --user test --password testing > testingdb.sql

Import dump files to Database or Import

  Terminal : mysql -u root -p testing_new < testingdb.sql


DataBase Dump & Restore for POSTGRESQL
 
Take dump from database or Export 

  Terminal : pg_dump -h localhost -U postgres -d testing > testdb.sql

Import dump files to Database or Import
 
  Terminal : psql -h localhost -U postgres -d testing_new < testdb.sql

Interactor in Rails

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