Search code examples
ruby-on-railsactiveadmincancancancancan

Rails - ActiveAdmin & CanCan custom override method for initialize_cancan_ability


I am attempting to pass thru request data to the Ability model as suggested here:

class ApplicationController < ActionController::Base
  #...

  private

  def current_ability
    @current_ability ||= Ability.new(current_user, request.remote_ip)
  end
end

and here:

class Ability
  include CanCan::Ability

  def initialize(user, ip_address=nil)
    can :create, Comment unless BLACKLIST_IPS.include? ip_address
  end
end

See: https://github.com/ryanb/cancan/wiki/Accessing-request-data

However, I am using ActiveAdmin with the CancanAdapter, and it uses a separate initialize call via:

def initialize_cancan_ability
  klass = resource.namespace.cancan_ability_class
  klass = klass.constantize if klass.is_a? String
  klass.new user
end

See: https://github.com/activeadmin/activeadmin/blob/master/lib/active_admin/cancan_adapter.rb

So how/where can I redefine initialize_cancan_ability so that I can pass in request data similar to the current_ability example?

Basically I'm hoping to just replace the last line as such:

klass.new user, request

Thanks.


Solution

  • You can create a file under lib/monkey_patches/active_admin.rb and put your overridden method there:

    require 'cancan'
    
    # Add a setting to the application to configure the ability
    ActiveAdmin::Application.inheritable_setting :cancan_ability_class, "Ability"
    
    module ActiveAdmin
        private
    
        def initialize_cancan_ability
          klass = resource.namespace.cancan_ability_class
          klass = klass.constantize if klass.is_a? String
          klass.new user, request
        end
    
      end
    
    end