Rails - ActiveAdmin& CanCan自定义覆盖initialize_cancan_ability的方法

时间:2015-09-18 21:07:32

标签: ruby-on-rails activeadmin cancan cancancan

我正在尝试将请求数据传递给Ability模型,如下所示:

class ApplicationController < ActionController::Base
  #...

  private

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

在这里:

class Ability
  include CanCan::Ability

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

请参阅:https://github.com/ryanb/cancan/wiki/Accessing-request-data

但是,我将ActiveAdmin与CancanAdapter一起使用,它通过以下方式使用单独的初始化调用:

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

请参阅:https://github.com/activeadmin/activeadmin/blob/master/lib/active_admin/cancan_adapter.rb

那么我如何/在哪里重新定义initialize_cancan_ability以便我可以传递类似于current_ability示例的请求数据?

基本上我希望只是替换最后一行:

klass.new user, request

感谢。

2 个答案:

答案 0 :(得分:0)

您可以在lib/monkey_patches/active_admin.rb下创建一个文件,并将重写的方法放在那里:

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

答案 1 :(得分:0)

如果您使用Devise,则可以从用户模型user.current_sign_in_ip

访问Ip