Tuesday, 26 November 2019

Error Handling in rails


Error Handling — Modular Approach



1. app/controllers/application_controller.rb
        class ApplicationController < ActionController::Base
        # Prevent CSRF attacks by raising an exception.
        # For APIs, you may want to use :null_session instead.
        protect_from_forgery with: :exception
        include Error::ErrorHandler
     end
 
2. Let’s refactor the ErrorModule to accommodate multiple
    error handling blocks. It looks much cleaner this way.
     lib/error/error_handler.rb
       # Error module to Handle errors globally
      # include Error::ErrorHandler in application_controller.rb
# Refactored ErrorHandler to handle multiple errors
# Rescue StandardError acts as a Fallback mechanism to handle any exception
module Error
  module ErrorHandler
    def self.included(clazz)
      clazz.class_eval do
        rescue_from ActiveRecord::RecordNotFound do |e|
          respond(:record_not_found, 404, e.to_s)
        end
        rescue_from StandardError do |e|
          respond(:standard_error, 500, e.to_s)
        end
      end
    end

    private
    
    def respond(_error, _status, _message)
      json = Helpers::Render.json(_error, _status, _message)
      render json: json
    end
  end
end
 
3. Define your own Exception (lib/error/custom_error.rb)
module Error
  class CustomError < StandardError
    attr_reader :status, :error, :message

    def initialize(_error=nil, _status=nil, _message=nil)
      @error = _error || 422
      @status = _status || :unprocessable_entity
      @message = _message || 'Something went wrong'
    end

    def fetch_json
      Helpers::Render.json(error, message, status)
    end
  end
end
 
Custom Error File Name:- (lib/error/not_visible_error.rb)
module Error
  class NotVisibleError < CustomError
    def initialize
      super(:you_cant_see_me, 422, 'You can\'t see me')
    end
  end
end
 
4. 404 and 500
You can handle common exceptions like 404 and 500, although it’s totally up to the developer. We need to create a separate controller class, ErrorsController for it.
Error Controller File Name:-(controllers/errors_controller.rb)
class ErrorsController < ApplicationController
  def not_found
    render json: {
      status: 404,
      error: :not_found,
      message: 'Where did the 403 errors go'
    }, status: 404
  end

  def internal_server_error
    render json: {
      status: 500,
      error: :internal_server_error,
      message: 'Houston we have a problem'
    }, status: 500
  end
end
5. We just have to add the following line to application.rb.
        config.exceptions_app = routes 
 6. Tell Rails to use Routes to resolve exceptions.
      Rails.application.routes.draw do
       get '/404', to: 'errors#not_found'
       get '/500', to: 'errors#internal_server_error'

       root 'home#index'
       get 'not_visible', to: 'home#not_visible'

     end
Now 404 exceptions fallback to errors#not_found and 500 to errors#internal_server_error.


Error Handling Link:-
https://medium.com/rails-ember-beyond/error-handling-in-rails-the-modular-way-9afcddd2fe1b

Pundit Gem in rails for authorization


Pundit Gem 

1. Add pundit gem in your Gemfile. gem "pundit"
2. Run Command bundle install.
3.  Include Pundit in your application controller:
       
class ApplicationController < ActionController::Base
          include Pundit
          protect_from_forgery
   
            (For Error Message)
            rescue_from Pundit::NotAuthorizedError, 
            with: :user_not_authorized
            def user_not_authorized
            flash[:warning] = "You are not authorized to perform this
              action."
            redirect_to(request.referrer || root_path)
          end
        end

4.  Optionally, you can run the generator, which will set up
     an application policy with some useful defaults for you:
         
rails g pundit:install

         After generating your application policy, restart the Rails  

         server so that Rails can pick up any classes in the new  
         app/policies/ directory.

5.  We suggest that you put these classes in app/policies.
     File name:- (app/policies/user_policy.rb) 
      
       
class UserPolicy < ApplicationPolicy
          attr_reader :current_user
     
          def initialize(current_user, user)
            @current_user = current_user
            @user = user
          end   

          def index?
           (@current_user.has_role? :administrator) ||  

           (@current_user
           ==  @user)
          end

          def show?
            false
          end

          def create?
            false
          end

          def new?
            create?
          end

          def update?
            (@current_user.id == @user.id) || 
            ((@current_user.has_role? :administrator) and not 
            (@user.has_role? :administrator))
          end

          def edit?
            (@current_user.id == @user.id) || 
            ((@current_user.has_role? :administrator) and not       
            (@user.has_role? :administrator))
          end

          def destroy?
            (@current_user.id == @user.id) || 
            ((@current_user.has_role? :administrator) and not
            (@user.has_role? :administrator))
          end 
        end

6.  The authorize method automatically infers that User will  

     have a matching UserPolicy class, and instantiates this   
     class, handing in the current user and the given record.  
      File Name:-  (controllers/users_controller.rb)
         
def index
            authorize @user
          end

          def edit
            authorize @user
          end
           
          def update
            if @user.update(user_params)
              redirect_to user_path(@user), notice: 'User was
                successfully updated.'
              authorize @user
            else
              render :edit, alert: "Sorry. Something isn't right."
            end
          end

          def destroy
            if @user.destroy
              redirect_to users_path, notice: 'User was successfully 
                destroyed.'
              authorize @user
            else
              redirect_to user_path(@user), alert: "Sorry. Something isn't  

               right."
            end
          end

7.  Policy File Name:- (app/policies/event_policy.rb)


       
class EventPolicy < ApplicationPolicy
          attr_reader :current_user

          def initialize(current_user, event)
            @current_user = current_user
            @event = event
          end

          def update?
            (@current_user.has_role? :administrator)
          end
             
          def edit?
            (@current_user.has_role? :administrator)
          end

          def destroy?
            (@current_user.has_role? :administrator)
          end 
        end

8.  Controller File Name:-  (events_controller.rb)


       
class EventsController < ApplicationController

          def edit
            @event = Event.find params[:id]
            authorize @event
          end

          def update
            @event = Event.find(params[:id])
            authorize @event
             end

          def destroy
            @event = Event.find(params[:id])
            authorize @event
          end

        end

9. Policy File Name:- (app/policies/artist_policy.rb)


       
class ArtistPolicy < ApplicationPolicy
          attr_reader :current_user

          def initialize(current_user, artist,user)
            @current_user = current_user
            @user = user
            @artist = artist
          end
           
          def update?
            ((@current_user.id == Artist.where(slug:
              @artist.slug).first.id) ||
            (@current_user.has_role? :administrator))
          end

          def edit?
            ((@current_user.id == Artist.where(slug:
               @artist.slug).first.id) ||
            (@current_user.has_role? :administrator))
          end

          def destroy?
            ((@current_user.id == Artist.where(slug:
                @artist.slug).first.id) ||
            (@current_user.has_role? :administrator))
          end
           
        end

Monday, 18 November 2019

React moment tag for datepicker/REACT-Day-PICKER

REACT-Day-PICKER

1. Install as dependency to use it in your project:
       npm install react-day-picker --save 

2. Then import the component and its style into your component:
      import DayPicker from 'react-day-picker';
 
     // Or import the input component
     import DayPickerInput from 'react-day-picker/DayPickerInput';

     import 'react-day-picker/lib/style.css';
 
3.  import DayPicker from 'react-day-picker';
   // Or import the input component
    import DayPickerInput from 'react-day-picker/DayPickerInput';
    import 'react-day-picker/lib/style.css';
    import MomentLocaleUtils, {formatDate,parseDate} from 'react-day-picker/moment';
    import 'moment/locale/it';

4. <DayPickerInput inputProps={{ className: 'form-control' }}
 formatDate={formatDate}
 parseDate={parseDate}
 format="LL"
 placeholder={`${formatDate(new Date(),'LL')}`}
 dayPickerProps={{
  localeUtils: MomentLocaleUtils,
 }}
    />

 React moment tag for datepicker

1. Installing :- npm install --save moment react-moment
2. Timezone support:- npm install --save moment-timezone
3. import Moment from 'react-moment';
4. 
 

Sunday, 17 November 2019

How to use datepicker gem in rails

 How to use datepicker gem in rails



1. Include bootstrap-datepicker-rails in Gemfile
     gem 'bootstrap-datepicker-rails'

2. Add this line to app/assets/stylesheets/application.css
   *= require bootstrap-datepicker3

3. Add this line to app/assets/javascripts/application.js
     //= require jquery3
     //= require bootstrap-sprockets
    //= require bootstrap-datepicker 



Thursday, 7 November 2019

ssh key open cmd in terminal

ssh key open cmd in terminal 

cat ~/.ssh/id_rsa.pub 

How to heroku database import 

heroku pg:backups:capture
heroku pg:backups:download
pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d mydb latest.dump

  Common Git Commands   Take clone of a repository git clone <remote-repository-url> ex: git clone  https://github.com/agricor/RegTech...