在gem中使用CanCan

时间:2013-05-06 19:33:20

标签: ruby-on-rails ruby-on-rails-3 gem cancan

我不确定这是否可行,但我想在我自己的宝石中使用CanCan。我尝试过以下代码:

module DynamicMenu
  require 'engine' if defined?(Rails)
  require 'cancan'

    module MenuItems
      #The new dynamic_menu encapsulates 
      class DynamicMenu
    def initialize
    @actionMenuItems ||= []
    end

    def newmenuitem(name,link,method=:get,confirm="Are you sure?")
          genlink = ""

          if method==:delete
            genlink += "<a href=\"#{link}\" data-confirm=\"#{confirm}\" data-method=\"delete\" rel=\"nofollow\">
     #{name}</a>".html_safe
          elsif link==:submit
            genlink += "<a href=\"#\" data-submit=\"true\">#{name}</a>".html_safe
          elsif link == :back
            genlink = "<a href=\"#\" data-back=\"true\">#{name}</a>".html_safe
          else
           genlink = "<a href=\"#{link}\">#{name}</a>".html_safe
          end      
  @actionMenuItems << genlink.html_safe
end

    def newCanCanProtectedItem(name,link,method=:get,confirm="Are you sure?")
       actions = Rails.application.routes.recognize_path(link)
    if defined?(CanCan) and can? actions[:action],actions[:controller].singularize.capitalize
        newmenuitem(name,link,method,confirm)
     else
       @actionMenuItems << "CANCAN NOT DEFINED OR ABILITY.RB PROBLEM";
     end
end

    def getItems
   return @actionMenuItems
    end

  end


  end
end

执行此操作时,我得到未定义的方法can?

1 个答案:

答案 0 :(得分:0)

CanCan需要依靠能力等级。所以,不知何故,你需要包括一个能力类。基础知识看起来像:

 class Ability
 include CanCan::Ability
     def initialize(user)
     end
 end

我使用了一个假设,但这应该是一个初始化器或类似的东西,该类被称为能力。

在gem中使用CanCan时,你必须创建一个能力类的新实例,或者传入它。我做了:

ability = Ability.new(current_user) #You have to pass in a user

必须传入用户。但是,似乎current_user未在gem的范围内定义。所以,我也将用户传递给了我的方法。

之后我能够做到:

ability.can? actions[:action],actions[:controller].singularize.capitalize