Wednesday, March 24, 2021

Ruby on Rails - Part 2 - CRUD with Rest standards and Pagination

1) Complete the quick start guide: 

https://localboyfrommadurai.blogspot.com/2021/03/ruby-on-rails-quick-start.html


2) Open Gemfile and the following line

gem 'kaminari'

This library helps for pagination


3) Install the gem:

bundle install


4) Modify app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

    protect_from_forgery with: :null_session

end

Adding this will allow the requests such as PUT, POST and DELETE calls without session authentication.


5) Modify config/routes.rb

Rails.application.routes.draw do

  get 'users(/:page_no)' => 'users#list', :defaults => { :page_no => 1 }

  delete 'users/:user_id' => 'users#delete'

  put 'users/:user_id' => 'users#update'

  post 'users' => 'users#create'

end


6) Modify app/controllers/users_controller.rb

class UsersController < ApplicationController

    def update

        params.require(:name)

        user = User.find(params[:user_id])

        if user

            user.update(name: params[:name])

            render json: {}, status: :ok

            return

        end

        render json: {}, status: :not_found

    end


    def create

        params.require(:name)

        user = User.create({:name => params[:name]})

        render json: user, status: :ok

    end


    def list

        @users = User.page(params[:page_no]).per(5)

        render 'users/list'

    end



    def delete

        User.delete(params[:user_id])

        render json: {}, status: :no_content

    end

end


7) Modify app/views/users/list.html.erb

<h1>Users</h1>


<ul>

  <% @users.each do |user| %>

    <li>

      <div><b>ID: </b><%= user.id %> </div>

      <div><b>Name: </b><%= user.name %> </div>

    </li>

  <% end %>

</ul>


Results:






Happy coding :)


Wednesday, March 17, 2021

Ruby on Rails quick start!

1) Create an application and run it!
rails new blog --skip-bundle
cd blog
bundle config set --local path 'vendor/bundle'
bundle install
rails webpacker:install
rails s

2) Create an API:

Add routes in config/routes.rb    
Rails.application.routes.draw do
  get 'users' => 'users#index'
end

Add a controller at app/controllers/users_controller.rb

class UsersController < ApplicationController
    def index
        render :json => 'Users Page'
    end
end

3) To render a template:

Create a html file in app/views/users/index.html.erb
<h1>Users Index</h1>

Modify app/controllers/users_controller.rb to render the template
class UsersController < ApplicationController
    def index
        render 'users/index'
    end
end


4) Connecting to database!

Modify config/database.yml

default: &default
  adapter: mysql2
  encoding: utf8
  database: your_database_name
  pool: 5
  host: 127.0.0.1
  username: root
  password: 
  slave:
    host: 127.0.0.1 

development:
  <<: *default

Add the following line in Gemfile
gem 'mysql2'
Install this gem
bundle install
Add a users model and start the server

rails generate model user
rails s

Add a column in the migration file at db/migrate/xxxxx_create_users.rb

class CreateUsers < ActiveRecord::Migration[6.1]

  def change

    create_table :users do |t|

      t.string :name

      t.timestamps

    end

  end

end


In config/routes.rb add a route to list the users

Rails.application.routes.draw do

  get 'users/list' => 'users#list'

  get 'users' => 'users#index'

end


In app/controllers/users_controller.rb add the code to create and query from database

class UsersController < ApplicationController

    def index

        name = 'User ' + rand(1..10000).to_s

        User.create({:name => name})

        render 'users/index'

    end

    def list

        @users = User.all

        render 'users/list'

    end

end


Create a view to render the users in app/views/users/list.html.erb

<h1>Users</h1>


<ul>

  <% @users.each do |user| %>

    <li>

      <%= user.name %>

    </li>

  <% end %>

</ul>


Run migration and start the server

rails db:migrate

rails s


Open http://localhost:3000/users and refresh the page several times to create new users

Open http://localhost:3000/users/list to view the list of users created



Happy coding!







Sunday, March 29, 2020

The two faces of the Corona Virus

The bad face:

     As of today (29th March) 31K humans have died because of the Corona virus. The entire world is on lockdown and most of the world population is struggling to survive.

The good face:
  • Over 90 cities in India including Delhi has recorded minimal air pollution in the last few days.
  • Satellite images released by NASA and the European Space Agency reveal that air pollution over China has gone down since the coronavirus outbreak.
  • Scientists and researchers are reporting a significant decrease in NO2 levels above Italy
  • Italians in Venice are looking to the city’s canals, which have turned crystal clear since boat traffic was halted. The fish are visible, the swans returned
  • The OZone layer of the planet is healing!

     
  • India's capital city Delhi's Air Quality Index is drastically improving


How did this happen?

  • Our usage of non-renewable energies came down drastically (Reduced Air pollution)
  • We stopped polluting water bodies. (Reduced Water pollution)
  • We stopped cutting trees. (Reduced Soil pollution)

What if it continues for 2 more months?

The earth is healing rapidly fast. Corona has served as an antivirus to protect the Earth from the Human viruses. I feel if we are locked down for 2 more months, the Earth's lifespan can increase by a few thousand years.


What we should continue doing after it's all over?:
  • Move away from non-renewable energy and use renewable energies. (Reduced Air pollution)
  • Protect the water bodies around us.  (Reduced Water pollution)
  • Protect the trees around us (Reduced Soil pollution)
  • Boycott plastics (Reduced Water and Soil pollution)


Stay indoors. Protect yourself, Protect the earth!


References:


Saturday, January 4, 2020

Reinhard Zumkeller's property of Fibbinary numbers n^2n^3n=0

Today I re-discovered an interesting property.

"If n is a fibbinary number, then n ^ 2n ^ 3n = 0".

Reinhard Zumkeller had already invented this property in 2005. I came to know this only after 20 days after publishing this post.

Background:

     Fibbinary numbers are integers whose binary representation contains no consecutive ones. 

     First few fibbinary numbers are as follows: 0, 1, 2, 4, 5, 8, 9, 10, 16, 17, 18..

     3, 6, 7, 10, 11... are not fibbinary numbers because they have two adjacent 1s in it's binary representation.


Proof:

     Fibbinary numbers have a property n & (n >> 1) = 0 (Because 0's and 1's cancel out each other when we do AND operation)

     We have n & (n >> 1) = 0

     this can also be rewritten as

     n & (n << 1) = 0

     n & 2n = 0

     We also know if a & b == 0 then a^b = a+b

     Now assume a is n and b is 2n. We get

 .    n ^ 2n = 3n

     Therefore n ^ 2n ^ 3n = 0 for all fibbinary numbers.



Math is fun!

Thursday, November 7, 2019

Competitive programming quickstart guide



How to become a Competitive Programmer in 2 hours:

This guide works for you if you are have never solved problems online before and you know how to code a `for loop` and you know what `arrays` are in any programming language.


Step 1: Register in ProjectEuler and solve this problem. You can solve this offline and submit the solution in the textbox. This should take you 15 minutes.

Step 2: Solve this problem and submit the solution in the text box. This should take you 30 minutes.

Step 3: Register in SPOJ and solve this problem. Note that you've to submit your source code. This should take you 15-30 minutes.

Step 4: Solve this problem and submit your source code. This should take you 30 minutes.

You can spend the remaining time in any problem in case you get stuck. 

Congrats! You are officially a competitive programmer now.


  • Let me know if this guide worked for you in comments and let me know how long it took for you.
  • If you are able to complete this guide, you can gradually increase difficulty and practice on your way to become a topcoder!