Quick and Dirty Authority to Pundit Conversion Script

November 18, 2019 ยท View on GitHub

task authority_to_pundit: :environment do

please note, this script was hastily created and does not convert everything but makes a good start to save some time

get list of models first because eager loading will crash later after the script modifies code

Rails.application.eager_load! policies = ApplicationRecord.subclasses.map { |item| { class_name: item.name, policy_name: item.name.underscore } }

move authorizers to policies

if File.exist?(Rails.root.join('app', 'authorizers')) FileUtils.mv Rails.root.join('app', 'authorizers'), Rails.root.join('app', 'policies') end

search and replace known patterns

search_and_replace 'include Authority::Abilities', '' search_and_replace 'include Authority::UserAbilities', '' search_and_replace 'authorize_action_for', 'authorize' search_and_replace 'Authorizer < ApplicationAuthorizer', 'Policy < ApplicationPolicy' search_and_replace '# class rules', ''

search_and_replace 'def self.creatable_by?(_user)', 'def create?' search_and_replace 'def self.creatable_by?(user)', 'def create?'

search_and_replace 'def self.readable_by?(_user)', 'def show?' search_and_replace 'def self.readable_by?(user)', 'def show?'

search_and_replace 'def self.updatable_by?(_user)', 'def update?' search_and_replace 'def self.updatable_by?(user)', 'def update?'

search_and_replace 'def self.deletable_by?(_user)', 'def destroy?' search_and_replace 'def self.deletable_by?(user)', 'def destroy?'

search_and_replace 'Authorizer, type: :authorizer do', 'Policy, type: :policy do' system "find . -type f -name "*authorizer.rb" -print0 | xargs -0 sed -i '' -e 's/resource/record/g'"

add missing policies

policies.each do |policy| path = Rails.root.join('app', 'policies', "#{policy[:policy_name]}_policy.rb") legacy_path = Rails.root.join('app', 'policies', "#{policy[:policy_name]}_authorizer.rb") next if File.exist?(path) || File.exist?(legacy_path)

open(path, 'w') do |file|
  file << "class #{policy[:class_name]}Policy < ApplicationPolicy \n"
  file << "end\n"
end

end

rename authorizers to policies

files_to_rename = Dir.glob(Rails.root.join('app', 'policies', '*_authorizer.rb')) files_to_rename.each do |file_to_rename| next if file_to_rename.include?('application_authorizer.rb')

FileUtils.mv file_to_rename, file_to_rename.gsub('_authorizer.rb', '_policy.rb')

end

remove old config

config_file = Rails.root.join('config', 'initializers', 'authority.rb') File.delete config_file if File.exist?(config_file) end

def search_and_replace(search_string, replace_string) system "find . -type f -name "*.rb" -print0 | xargs -0 sed -i '' -e 's/#{search_string}/#{replace_string}/g'" end