LUG Programming

Page 109

def current_album @current_album ||= (session[:album_id] ? find_album(session[:album_id]) : nil) end helper_method :current_album= def current_album=(id) if current_user session[:album_id] = id else session[:album_id] = nil end end helper_method :all_albums def all_albums if current_user return current_user.albums else return Album.find(:all, :order => "id DESC", :limit => 20 ) end end helper_method :all_pictures def all_pictures if current_user return current_user.pictures else return Picture.find(:all, :order => "id DESC", :limit => 20 ) end end helper_method :user_albums def user_albums if current_user return current_user.albums else return [] end end helper_method :current_user_owns? def current_user_owns?(item) logged_user = current_user return true if logged_user && logged_user.id == item.user_id false end end

We added a line to the logout method to remove the :album_id in the session object. Although we want to track the current album, we only want to do so when the user is logged in. Then we added a current_album helper method which works just like the current_user, and we also add an assignment helper method current_album=. We also added helper methods for all_albums and all_pictures, which will give back different results depending whether the visitor is logged in or not. We added a helper method to get the user_albums for the logged in user. Note that when the visitor is not logged in, we limit the results to the latest 20 albums or pictures. Finally, we added a current_user_owns? helper method to check if the currently logged in user owns the album or picture. Now we'll move on and modify the newly generated controller. Again, as for the UsersController, the modifications are fairly superficial, so I won't show the code here. Copyright Š John Leach 2008. All rights reserved.

109


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.