views:

118

answers:

2

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 @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

A: 

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.

Senthil
+1  A: 

Hello

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.

fjuan
No, I haven't, but that's a lot more DRY. Thanks.
Senthil