class Boring::Pundit::InstallGenerator

Public Instance Methods

add_pundit_gem() click to toggle source
# File lib/generators/boring/pundit/install/install_generator.rb, line 15
def add_pundit_gem
  say "Adding Pundit gem", :green
  Bundler.with_unbundled_env do
    run "bundle add pundit"
  end
end
after_run() click to toggle source
# File lib/generators/boring/pundit/install/install_generator.rb, line 70
def after_run
  unless options[:skip_rescue]
    say "\nPlease check the `application_controller.rb` file and fix any potential issues"
  end

  say "\nDon't forget, that you can generate policies with \nrails g pundit:policy Model\n"
end
ensure_policies() click to toggle source
# File lib/generators/boring/pundit/install/install_generator.rb, line 36
def ensure_policies
  return if options[:skip_ensuring_policies]

  say "Force ensuring policies", :green
  inject_into_file 'app/controllers/application_controller.rb', after: "include Pundit\n" do
    "  after_action :verify_authorized\n"
  end
end
inject_pundit_to_controller() click to toggle source
# File lib/generators/boring/pundit/install/install_generator.rb, line 29
def inject_pundit_to_controller
  say "Adding Pundit module into ApplicationController", :green
  inject_into_file 'app/controllers/application_controller.rb', after: "class ApplicationController < ActionController::Base\n" do
    "  include Pundit\n"
  end
end
rescue_from_not_authorized() click to toggle source
# File lib/generators/boring/pundit/install/install_generator.rb, line 45
      def rescue_from_not_authorized
        return if options[:skip_rescue]

        say "Adding rescue from Pundit::NotAuthorizedError", :green

        after = if File.read('app/controllers/application_controller.rb') =~ (/:verify_authorized/)
                  "after_action :verify_authorized\n"
                else
                  "include Pundit\n"
                end

        inject_into_file 'app/controllers/application_controller.rb', after: after do
          <<~RUBY
            \trescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

            \tprivate

            \tdef user_not_authorized
            \t  flash[:alert] = "You are not authorized to perform this action."
            \t  redirect_to(request.referrer || root_path)
            \tend
          RUBY
        end
      end
run_pundit_generator() click to toggle source
# File lib/generators/boring/pundit/install/install_generator.rb, line 22
def run_pundit_generator
  return if options[:skip_generator]

  say "Running Pundit Generator", :green
  run "DISABLE_SPRING=1 rails generate pundit:install"
end