Links to my new site shivab.com

Advertisements

Installing and configuration of Nginx Web/(Reverse proxy) server in ubuntu

First you will have to install ubuntu

$ sudo apt install nginx

this will install the software and it will generate default configurations in /etc/nginx/site-available folder. You can see those files there. You can modify the default.conf file. Default content is

# Default server configuration
#
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        # SSL configuration
        #
        # listen 443 ssl default_server;
        # listen [::]:443 ssl default_server;
        #
        # Note: You should disable gzip for SSL traffic.
        # See: https://bugs.debian.org/773332
        #
        # Read up on ssl_ciphers to ensure a secure configuration.
        # See: https://bugs.debian.org/765782
        #
        # Self signed certs generated by the ssl-cert package
        # Don't use them in a production server!
        #
        # include snippets/snakeoil.conf;

        root /var/www/html;

        # Add index.php to the list if you are using PHP
        index index.html index.htm index.nginx-debian.html;

        server_name _;

        location / {
                # First attempt to serve request as file, then
                # as directory, then fall back to displaying a 404.
                try_files $uri $uri/ =404;
        }

        # pass PHP scripts to FastCGI server
        #
        #location ~ \.php$ {
        #       include snippets/fastcgi-php.conf;
        #
        #       # With php-fpm (or other unix sockets):
        #       fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
        #       # With php-cgi (or other tcp sockets):
        #       fastcgi_pass 127.0.0.1:9000;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #       deny all;
        #}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#       listen 80;
#       listen [::]:80;
#
#       server_name example.com;
#
#       root /var/www/example.com;
#       index index.html;
#
#       location / {
#               try_files $uri $uri/ =404;
#       }
#}

To configure reverse proxy

server {
  listen 80;
  listen [::]:80;

  server_name example.com;

  location / {
      proxy_pass http://localhost:3000/;
  }
}

here, your application server is running at port 3000 in localhost.

Problems I faced

I was trying to serve the Rails app from folder other than /var/www like /root/projects/production/myapp dir, but the nginx could not render the app. It return the permission denined issue. I changed the owner of all the folders and files and also I changed the file permission to 777. But I failed.

So I moved the project to /var/www

How I Hosted Rails app

I moved the rails app to /var/www and set the permission to chmod -R 755 /myapp

node-pre-gyp ERR! build error | yarn install | Rails | Mac – Mojave

I encountered a series of errors when I tried to run my existing Rails5 app in my freshly installed macOS Mojave.

$ bundle exec rails s

this generated some errors like, node not found, then I installed node using brew.

$ brew install node

then,

$ npm install yarn
$ yarn install 
gyp ERR! build error
gyp ERR! stack Error: `make` failed with exit code: 2
gyp ERR! stack     at ChildProcess.onExit (/Users/john/projects/sifaris/node_modules/node-gyp/lib/build.js:262:23)
gyp ERR! stack     at ChildProcess.emit (events.js:196:13)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:256:12)
gyp ERR! System Darwin 18.5.0
gyp ERR! command "/usr/local/Cellar/node/12.1.0/bin/node" "/Users/john/projects/sifaris/node_modules/node-gyp/bin/node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library="
gyp ERR! cwd /Users/john/projects/sifaris/node_modules/node-sass
gyp ERR! node -v v12.1.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
$ bundle exec rails s
=> Booting Puma
=> Rails 5.2.3 application starting in development
=> Run `rails server -h` for more startup options
error Lockfile does not contain pattern: "yarn@^1.15.2"
error Couldn't find an integrity file
error Found 2 errors.


========================================
  Your Yarn packages are out of date!
  Please run `yarn install --check-files` to update.
========================================

Solution

$ rm yarn.lock
$ yarn cache clean
$ yarn install
$ yarn install v1.15.2

now it installs all the dependencies properly

bundle exec rails s
=> Booting Puma
=> Rails 5.2.3 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.1 (ruby 2.6.0-p0), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://localhost:3000
Use Ctrl-C to stop
yarn install v1.15.2

Rails | Apartment gem | Resets AR objects when tenant switched

I ran into a weird situation today. Active Record objects stored in vars are removed when I switched from one tenant to another on the fly. This will create a weird test-failing scenario and you never know why its happening.

def switch(name)
  yield(name)
end

@customers = [1,2,3]
switch('shiva') do |name|
  puts name
  puts @customers
end

# Gives output
# shiva
# 1
# 2
# 3

 

but when I do this

@roles     = Role.all
@customers = org.branches
@list      = [1, 2]

puts 'Role count' + @roles.count.to_s
puts 'Customer count' + @customers.count.to_s
puts 'list count' + @list.count.to_s

Apartment::Tenant.switch!(org.database_name)
puts '-------'
puts 'Role count' + @roles.count.to_s
puts 'Customer count' + @customers.count.to_s
puts 'list count' + @list.count.to_s

output is

Role count2
Customer count2
list count2
-------
Role count0
Customer count0
list count2

 

Reason

# apartment-2.2.0/lib/apartment/adapters/abstract_adapter.rb
#   Switch to a new tenant
#
#   @param {String} tenant name
#
def switch!(tenant = nil)
  run_callbacks :switch do
    return reset if tenant.nil?

    connect_to_new(tenant).tap do
      Apartment.connection.clear_query_cache
    end
  end
end

Rails : PaperTrail gem : Custom events to track fields changed

In my project, I was asked to keep track of changes in records. I found PaperTrails gem, and its found to be pretty useful.

But it lacks a straightforward feature to know the fields changed in that particular version. Then I thought to write custom event name so that I could grep the field_name I wish to check.

# == Schema Information
#
# Table name: tasks
#
#  id                :integer          not null, primary key
#  worker_id         :integer
#  customer_id       :integer
#  kind              :integer          default(0)
#  status            :integer          default(0)
#  note              :text
#  start_on          :datetime
#  complete_on       :datetime
#  started_on        :datetime
#  completed_on      :datetime
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#  driver_acceptance :integer          default(0)
#  refuel_id         :integer
#  shift_id          :integer
#

class Task < ActiveRecord::Base
  include Timeable
  has_paper_trail
  
  # Update event-name on update
  before_save :paper_trail_events, on: :update

  enum status: { scheduled: 0, started: 1, skipped: 2, completed: 3, paused: 4, rescheduled: 5 }
  enum kind: { inter_location: 0, refuel: 1, break: 2 }
  enum driver_acceptance: { pending: 0, accepted: 1, rejected: 2, sent: 3 }

  private

    def paper_trail_events
      changed_fields         = self.changes.keys - ['created_at', 'updated_at']
      self.paper_trail_event = "Updated #{changed_fields.join(',')}"
    end
end

In Rails Console

> Task.find(1768).versions.map &:event
=> ["Updated start_on,complete_on,status", "Updated worker_id"]

 

Invalid CSS after “(min-width: “: expected expression (e.g.

Two possible reasons:

  • You might be @importing minified version of css assets like bootstrap.min.css
    • I did same and later solved using normal version css file
  • Search the suspect file if it has the content (min-width: and (max-width on the same line
    • see if there is any variable used
    • there might be px unit missing after the var
    • see if there is any possibility of var being nil
    • use @if condition to solve problem
    • eg:
@if  $min != null and $max != null{
  @media (min-width: $min + 'px') and (max-width: $max + 'px') {
    @content;
  }
}

Ruby on Rails | Setup MS-SQL server in Ubuntu 17.04

MSSQL Server Installation

Follow these instructions https://www.rootusers.com/how-to-install-microsoft-sql-server-on-ubuntu-linux/

Note: During installation it will ask you for password, put a strong password remember it or note it down.

Reset Server Admin(SA) password

If you, unfortunately, forgot the SA password then you can reset follow the commands

$ sudo systemctl stop mssql-server
$ sudo /opt/mssql/bin/mssql-conf setup

Testing

If you wish to test if Server is installed and ready to receive requests

sqlcmd -S localhost -U sa -P your_strong_password

Install FreeTDS binaries

$ apt-get wget
$ apt-get install build-essential
$ apt-get install libc6-dev

$ wget ftp://ftp.freetds.org/pub/freetds/stable/freetds-1.00.21.tar.gz
$ tar -xzf freetds-1.00.21.tar.gz
$ cd freetds-1.00.21
$ ./configure --prefix=/usr/local --with-tdsver=7.3
$ make
$ make install

Install required gems

# SQL Server (2012 or higher required)
#
# Install the adapters and driver
#   gem install tiny_tds
#   gem install activerecord-sqlserver-adapter
#
# Ensure the activerecord adapter and db driver gems are defined in your Gemfile
#   gem 'tiny_tds'
#   gem 'activerecord-sqlserver-adapter'

If still, you cannot install the gem tiny_tds then try using sudo
$ sudo gem install tiny_tds -v '2.0.0'

Importing from Remote to Localhost db

Exporting from remote

bcp my_table_name out ~/my_table_name.txt -S yourdb.database.secure.windows.net -U yourusername -P 'YourStrongPassword123!!' -d mydbname -c -t ','

 

Import to Local

bcp my_table_name in ~/my_table_name.txt -S localhost -U sa -P 'PrashantBhusal1' -d my_local_db_name -c -t ',' -q

**Output When Successful**

Starting copy...

5 rows copied.
Network packet size (bytes): 4096
Clock Time (ms.) Total : 16 Average : (312.5 rows per sec.)

Useful links

https://askubuntu.com/questions/870927/sqlcmd-not-available-after-installing-mssql-tools

https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-troubleshooting-guide

https://docs.microsoft.com/en-us/sql/linux/sql-server-linux-troubleshooting-guide#connection

https://www.rootusers.com/how-to-install-microsoft-sql-server-on-ubuntu-linux/

https://github.com/rails-sqlserver/tiny_tds#install