Sha256: ef4e33d0c0b11514f2fdfd7e9e1e4e9c1187a71eedbb9dec7fce7ed719c3bbd1

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

module Authz
  class ControllerAction < ApplicationRecord

    # Validations
    # ==========================================================================
    validates :controller, presence: true
    validates :action, presence: true
    validates_uniqueness_of :controller, scope: %i[action]
    validate :controller_action_pair_exist

    # Associations
    # ==========================================================================
    has_many :business_process_has_controller_actions,
             class_name: 'Authz::BusinessProcessHasControllerAction',
             foreign_key: 'authz_controller_action_id'
    has_many :business_processes, through: :business_process_has_controller_actions
    has_many :roles, through: :business_processes
    has_many :role_grants, through: :roles

    # Class Methods
    # ==========================================================================
    # Introspects the application's routes and returns a list of hashes of all
    # reachable controller actions with the format
    # { "orders" =>["new", "edit", "update"] }
    def self.reachable_controller_actions
      result = {}
      routes = Rails.application.routes.set.anchored_routes.map(&:defaults).uniq
      routes.each do |route|
        controller = route[:controller]
        action = route[:action]
        if result.has_key? controller
          result[controller].push(action)
        else
          result[controller] = [action]
        end
      end
      result
    end

    # Instance Methods
    # ==========================================================================
    def to_s
      "#{controller}##{action}-#{id}"
    end

    private

    def controller_action_pair_exist
      unless self.class.reachable_controller_actions[controller].try(:include?, action)
        errors.add(:base, 'the controller action you are trying to save is not included in the routes')
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
authz-0.0.1.alpha app/models/authz/controller_action.rb