Friday 24 February 2017

Skip password validation of Devise gem.

In general if we need to skip validation we can do it by :

    user.save(validate: false)

validate: false skips validation from all the attributes.

But what if we need skip validation on particular field like password validation of devise gem.

In User.rb

    attr_accessor :skip_password_validation

    private

           def password_required?
                 return false if skip_password_validation
              super
           end

In registrations_controller.rb

    def configure_sign_up_params
        params.require(:user).permit(:email, :password, :password_confirmation, :skip_password_validation)
    end

Now, whenever you want to skip password validation, pass skip_password_validation params as true

    user.skip_password_validation = true
    user.save

It will create User without password.

Thursday 16 February 2017

Executing ubuntu shell commands in ruby programming


1. system
   
    The system method calls a system program. We have to provide the command as a string argument to this method.
    This will always return value is either true, false or nil.

    Example -
       
        system("df -h")
   
    Above command gives disk information but it will return true.

       Filesystem      Size  Used Avail Use% Mounted on
        udev            1.9G     0  1.9G   0% /dev
        tmpfs           386M  6.4M  380M   2% /run
        /dev/sda1       141G   74G   61G  56% /
        tmpfs           1.9G  523M  1.4G  28% /dev/shm
        tmpfs           5.0M  4.0K  5.0M   1% /run/lock
        tmpfs           1.9G     0  1.9G   0% /sys/fs/cgroup
        /dev/sda5       314G   67M  298G   1% /drive
        cgmfs           100K     0  100K   0% /run/cgmanager/fs
        tmpfs           386M   76K  386M   1% /run/user/1000
         => true

    system eats up all the exceptions. So the main operation never needs to worry about capturing an exception raised from the child process.

2. exec

    By using Kernel#exec replaces the current process by running the external command. The method can take a string as argument. When using     more than one argument, then the first one is used to execute a program and the following are provided as arguments to the program to be invoked.

    Example -

        exec 'date'

    Above command returns system date like this

         =>    Fri Feb 17 10:27:16 IST 2017

3. Backticks

    Backtick returns the standard output of the operation. As opposed to the above approach, the command is not provided through a string,         but by putting it inside a backticks pair.

    Example -

        `date`

    Above command returns system date like this

         =>    "Fri Feb 17 10:32:35 IST 2017\n"

    Backtick operation forks the master process and the operation is executed in a new process. If there is an exception in the sub-process then that exception is given to the main process and the main process might terminate if exception is not handled.

4. %x()

    Using %x is an alternative to the back-ticks style. It allows you to have different delimiter.

    Example -

        %x('date')

     Above command returns system date like this

         => "Fri Feb 17 10:37:14 IST 2017\n"

5. Open3.popen3

    Sometimes the required information is written to standard input or standard error and you need to get control over those as well. Here         Open3.popen3 comes is very usefull

    Example -

        require 'open3'
        cmd = 'git push origin master'
        Open3.popen3(cmd) do |stdin, stdout, stderr, wait_thr|
          puts "stdout is:" + stdout.read
          puts "stderr is:" + stderr.read
        end

6. $?

    You can check process status by running $?.

Thursday 9 February 2017

Response and exception handling in Rails 5 Api only.


We will use --api argument to tell Rails that we want an API application.

Create a rails 5 api application by running -

    $ rails new todos --api

Now, you can not that Make ApplicationController  inherit from ActionController::API  instead of ActionController::Base and it has not generated view files.

Now, generate a controller by using scaffold -

    $ rails g scaffold User first_name last_name

We will responds with JSON and an HTTP status code 200 by default. For this we will write it in concern.

In app/controllers/concerns/response.rb

    module Response
      def json_response(object, status = :ok)
        render json: object, status: status
      end
    end

Now, Suppose that we have to find a User by id. In this case where the record does not exist, ActiveRecord will throw an exception ActiveRecord::RecordNotFound. We'll rescue from this exception and return a 404 message.

Also, we will rescue ActiveRecord::RecordInvalid for the case of invalid record and it will return HTTP code 422.

So, make a module in app/controllers/concerns/exception_handler.rb -

    module ExceptionHandler
      extend ActiveSupport::Concern

      included do
        rescue_from ActiveRecord::RecordNotFound do |e|
          json_response({message: e.message}, :not_found)
        end

        rescue_from ActiveRecord::RecordInvalid do |e|
          json_response({message: e.message}, :unprocessable_entity)
        end

        rescue_from StandardError do |e|
          json_response({message: e.message}, :unprocessable_entity)
        end
      end
    end

Include these modules in the application controller.

    class ApplicationController < ActionController::API
      include Response
      include ExceptionHandler
    end

Now, in users controller we can use json_response helper for response.

    class UsersController < ApplicationController
      before_action :set_user, only: [:show, :update, :destroy]

      # GET /users
      def index
        @users = User.all
        json_response(@users)
      end

      # GET /users/1
      def show
        json_response(@user)
      end

      # POST /users
      def create
        @user = User.create!(user_params)
        json_response(@user, :created)
      end

      # PATCH/PUT /users/1
      def update
        @user.update(user_params)
        head :no_content
      end

      # DELETE /users/1
      def destroy
        @user.destroy
        head :no_content
      end

      private
      # Use callbacks to share common setup or constraints between actions.
      def set_user
        @user = User.find(params[:id])
      end

      # Only allow a trusted parameter "white list" through.
      def user_params
        params.permit(:first_name, :last_name)
      end
    end

Note that we are using create! instead of create because as we know that create! raise a exception.

You can customize the error message like this -

    def create
      user = User.new(user_params)
      if user.save
        json_response(user)
      else
            json_response({error: 'User has not created'}, :unprocessable_entity)
      end
    end



Saturday 4 February 2017

Elasticsearch with Rails 5


In this article, we will introduce you to Elasticsearch and show you how to install, configure and start using it with ruby on rails.

Elasticsearch is a platform for distributed search and analysis of data in real time. Its popularity is due to its ease of use, powerful features, and scalability.

Elasticsearch supports RESTful operations. This means that you can use HTTP methods (GET, POST, PUT, DELETE, etc.).

If it is your first time with Elasticsearch and you don't have Elasticsearch install in your system for this you can follow digital ocean documentation or you can simply install by

Update your ubuntu package

    $ sudo apt-get update

Download the latest Elasticsearch version, which is 2.3.1 at the time of writing.

    $ wget https://download.elastic.co/elasticsearch/release/org/elasticsearch/distribution/deb/elasticsearch/2.3.1/elasticsearch-2.3.1.deb

Then install it with dpkg.

    $ sudo dpkg -i elasticsearch-2.3.1.deb

To make sure Elasticsearch starts and stops automatically with the server, add its init script to the default runlevels

    $ sudo systemctl enable elasticsearch.service

Now that Elasticsearch and its Java dependencies have been installed, it is time to configure Elasticsearch. The Elasticsearch configuration files are in the /etc/elasticsearch directory.

To start editing the main elasticsearch.yml configuration file with nano or your favorite text editor.

    $ sudo nano /etc/elasticsearch/elasticsearch.yml

Remove the # character at the beginning of the lines for cluster.name and node.name to uncomment them, and then update their values

    . . .
    cluster.name: mycluster1
    node.name: "My First Node"
    . . .

These the minimum settings you can start with using Elasticsearch. However, it's recommended to continue reading the configuration part for more thorough understanding and fine-tuning of Elasticsearch.


Now, we will integrate elasticsearch with rails.

To get started, grab the latest Ruby on Rails and add following below gems to your Gemfile.

    gem 'elasticsearch-rails'
    gem 'elasticsearch-model'

Open the model file at app/models/user.rb, and add the Elasticsearch includes. This will allow us to use the Elasticsearch methods on our model, and will also enable the Elasticsearch callbacks for events such as creating, updating, and destroying our model objects, which will keep the Elasticsearch index up to date.

    class User < ActiveRecord::Base
        include Elasticsearch::Model
        include Elasticsearch::Model::Callbacks
    end

Now, we have to call the import method on the User model. This is needed because our search index is empty and we need to populate it with our current data. Any subsequent changes to the User table will automatically be added to the index by the Elasticsearch callbacks, so you wont need to run the import method again, unless changes are made outside of the Rails app.

So, Open up the rails console and run

    User.import

Now, you can start searching the User model. By default this will search all the columns in this model.

    User.search("abc").records