Featured Code Snippet #1
This code stems from the need to render (or do) something different based on the user’s authentication/authorization status. For example, if the user is not logged in, do not give them access to this action. Or, if the user is not an admin, show them this view, otherwise show them a different view. I accomplished this by adding two methods to my application controller: the first deals with authentication, the second with authorization. Let’s take a look:
def for_admin_only
unless @current_user
redirect_to(root_url)
else
yield
end
end
def for_users_by_type
if @current_user
yield :admin
else
yield :anonymous
end
end
These methods are consumed by the controller like so:
for_admin_only do
render :html => @posts
end
for_users_by_type do |type|
case type
when :anonymous
render :html => @posts
when :admin
render :template => 'admin/posts/index', :html => @posts
end
end
In the second snippet, we call for_admin_only first, which says that if the user is logged in, then run the specified snippet of code, otherwise redirect to the homepage (this could also redirect to a 403 page, or whatever else you prefer). Next, we call for_users_by_type, which passes back a type variable saying if the user is anonymous or admin. If the user is anonymous we render the basic view, if s/he’s an admin, we render the admin index view.
