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

Thursday, 28 June 2018

SMS integration using msg91 in ruby

require 'uri'
require 'net/http'

PARAMS

sender = 'RAJKMAR'
route = 4
mobiles = '91********'
authkey = '**********'
message = 'Your message'
country = '91'

API CALL:

url = URI("http://api.msg91.com/api/sendhttp.php?sender=#{sender}&route=#{route}&mobiles=#{mobiles}&authkey=#{authkey}&encrypt=&country=#{country}&message=#{message}")

http = Net::HTTP.new(url.host, url.port)

request = Net::HTTP::Get.new(url)

response = http.request(request)

Friday, 15 June 2018

Deploy rails application with nginx and unicorn server configurations

NGNIX SETUP With Rails Application
==================================
1. sudo apt-get install nginx

2. sudo vi /etc/nginx/sites-enabled/default -> Open config file

3.Update the below changes in nginx default file

root /home/rajkumar/Rajkumar/Projects/rajuthayaa
server_name localhost;
location @raj{
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_pass http://localhost:3001;
}

4. sudo service nginx start

5. if any errors in nginx kindly run the below command and check it.
 sudo vi /var/log/nginx/error.log



UNICORN SETUP With Rails Application
====================================
1. gem 'unicorn' in your gemfiles

2. create unicorn.rb in config/unicorn.rb

3. Update the below changes in unicorn.rb files

APP_PATH = "/home/rajkumar/Rajkumar/Projects/rajuthayaa"

working_directory APP_PATH
stderr_path APP_PATH + "/log/unicorn.stderr.log"
stdout_path APP_PATH + "/log/unicorn.stdout.log"

preload_app true

timeout 30

listen "/home/rajkumar/Rajkumar/Projects/rajuthayaa/shared/sockets/unicorn.rajutaya.sock", :backlog => 64

listen 3002, :tcp_nopush => true

pid  APP_PATH + "/unicorn.pid"

before_fork do |server, worker|
  defined?(ActiveRecord::Base) and
      ActiveRecord::Base.connection.disconnect!
end

after_fork do |server, worker|
  defined?(ActiveRecord::Base) and
      ActiveRecord::Base.establish_connection
end

upstream raj(raj){
server unix:/home/rajkumar/Rajkumar/Projects/rajuthayaa/shared/sockets/unicorn.rajutaya.sock fail_timeout=0;
}

4. Add upstream in nginx config files -->sudo vi /etc/nginx/sites-enabled/default

upstream raj(raj){
server unix:/home/rajkumar/Rajkumar/Projects/rajuthayaa/shared/sockets/unicorn.rajutaya.sock fail_timeout=0;
}

5. create shared/sockets inside your rails app

6. unicorn_rails -c config/unicorn.rb -D for run the unicorn server.

7. if any issues kindly check the log/unicorn.stderr.log files.

8. Restart both nginx and unicorn server it will work.

Wednesday, 6 June 2018

Unix setup in rails application

Unicorn setup for deployment

1. gem 'unicorn' add in gem file

2. create config/unicorn.rb file

3. paste this 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"

4. mkdir -p shared/pids shared/sockets shared/log

5. create script in /etc/init.d/unicorn_appname

6. sudo chmod 755 /etc/init.d/unicorn_appname

7. sudo update-rc.d unicorn_appname defaults

8. sudo service unicorn_appname start

Interactor in Rails

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