如何在 rails 中使用 helper 检查 rolify?

How to check rolify with a helper in rails?

我想为我的 rolify 方法制作一些助手。

因此,我创建了以下内容:

用户助手

模块 UsersHelper

    #Check if current user is admin

    def admin_check
      if current_user
      if current_user.has_role? :admin
     end
    end

    #Check if current user is pro and admin

    def admin_and_pro_check
      if current_user
      if current_user.has_any_role? :admin, :pro
     end
    end

    #Check if current user is pro

    def pro_check
      if current_user
      if (current_user.has_role? :pro) && (current_user.is_pro == true)
     end
    end
  end

end

现在,在我看来,我该如何使用它们?哪种方法更好?

<%= pro_check do %>
  <%= f.input :url, label: "Visto en", placeholder: "www.paginaweb.com" %>
<% end %>

<%= if pro_check %>
  <%= f.input :url, label: "Visto en", placeholder: "www.paginaweb.com" %>
<% end %>

我会将这些添加到用户模型中。缺点是如果你不断添加角色,这可能会变得非常难以维护。 这将使它更好用,并使真相检查更具可读性。

我还会在您的 current_user 方法中使用空对象模式,这样您就可以避免所有的 nil 检查。我讨厌重复的零检查,但如果你对它们没意见,那就完全忽略这个建议吧。

代码中的 if 检查大部分是不必要的,如下所示。

class User < ActiveRecord::Base
  #...
  def pro?
    self.has_role?(:pro) && self.is_pro == true
  end

  def admin?
    self.has_role? :admin
  end
end

此时您可以在 current_user 方法中 return 用户实例或空对象(如 avdi post 此处 http://devblog.avdi.org/2011/05/30/null-objects-and-falsiness/ 中所示的对象) 或者,如果您使用的是设计,您可以将专业支票嵌入 user_signed_in? 支票

这是设计示例

<% if user_signed_in? %>
  <% if current_user.pro? %>
    User is a pro
  <% elsif current_user.admin? %>
    User is an admin
  <% elsif current_user.admin? && current_user.pro? %>
    Current user is an admin and a pro
  <% else %>
    Current user is neither an admin nor a pro
  <% end %>
<% end %>

您当然可以创建自己的 user_logged_in? 方法来检查当前用户是否存在(如果您不使用设计)。我认为这是一个很好的可读方法名称。你可以把它放在 application_helper.rb

您的方法没有 return 任何东西。您想要一种 return 是真还是假的方法,我建议:

def admin_check
  current_user && current_user.has_role?(:admin)
end

def admin_and_pro_check
  current_user && current_user.has_any_role?(:admin, :pro)
end

def pro_check
  current_user && current_user.has_role?(:pro) && current_user.is_pro == true
end

然后你就可以像你认为的那样使用 then。