views:

21

answers:

1

The anti-pattern that I want to kill is:

- if !current_user
  # do something
- if !member
  # do something else
- if admin
  # blah blah blah
- else
  # Bored now.

I suspect the answer has something to do with view helpers and partials, but I'm wondering what some of the best practices and design patterns are. Thanks!

A: 

I do a lot from my controller:

before_filter :require_user

def require_user
  unless current_user
    store_location
    flash[:notice] = "You must be logged in to access this page"
    redirect_to login_url
    return false
  end
end

But depending on your role (admin, user, member ) you could perform the same task. That way, before the view is rendered, you're controller will take care of where they are to be directed.

Trip
Thanks Trip, I guess my use case is more about whether I want to show users a grey buttons, a disabled button, a blue button, or no button at all, based on the state of the current user. This isn't so much an issue of permissions or access control.
asoules
Couldn't you accomplish the same task through the controller through a before_filter. And based on the case of the method, it applies to what buttons they see in the view?
Trip
I probably could, but I don't like the idea of putting view-related code in controllers. I check permissions in the controller, but in my case, there are many states for the UI that have nothing to do with permissions, related to what the user has or hasn't done yet. In this situation I want to switch based on user state and either render different partials, use different CSS class names, or just display different text.
asoules