开发者

Can declarative authorization be used to hide/show certain fields?

开发者 https://www.devze.com 2022-12-19 00:48 出处:网络
I\'m trying to figure out the best way to hide certain fields in user profile based on user\'s preference. So far I\'m using a boolean field and an if, then statement.

I'm trying to figure out the best way to hide certain fields in user profile based on user's preference. So far I'm using a boolean field and an if, then statement.

<% if 开发者_JAVA技巧@user.show_email == 'true' -%>
  <%=h @user.email %>
<% else -%>
  hidden
<% end -%>

I was wondering if I could use declarative_authorization or some other better method that is more DRY. I prefer to have in a way like if @user.role == "admin" show all, if @user.role == "regular" show only non-hidden fields. etc

Thanks


Have you considered using a helper function? In your case, I would do something like this on app/helpers/user_helper.rb:

def show_attribute(user, attribute_name)
  preference = "show_#{attribute_name}"

  if current_user.has_role?(:admin) or 
     !user.respond_to?(preference) or
     (user.respond_to?(preference) and user.send(preference))

    return user.send(attribute_name)
  else
    return "hidden"
  end

end

You can use it in your views like this:

  <%=h show_attribute(@user, :email) %>
  <%=h show_attribute(@user, :address) %>

Best regards.


Someone slap me over the head for not reading the docs properly...it was right in front of my face.

You use the has_role? helper provided by d_a

<% if has_role?(:admin) %>
  show everything
<% else -%>
  show nothing
<% end -%>

I believe it passed in current_user automatically. So if current_user has role admin, its shows everything.

0

精彩评论

暂无评论...
验证码 换一张
取 消