Is this a case for inheritance?
I have Rails models User
, ReadingList
and SessionReadingList
. A user has many reading lists. A SessionReadingList
is a special type of reading list for before a user has registered, stored in the session.
In my ReadingListsController
every action is of the form:
def show
if current_user
#load user's reading lists
else
#load session reading list from session
end
end
I'm wondering whether I'd be better off subclassing ReadingListsController
so I have e.g. SessionReadingListsController
and UserReadingListsController
. I don't know how I'd handle the routing then though.
So, is subclassing the solution? If so, do I redirect from the R开发者_运维知识库eadingListsController
depending on current_user
? Or is there a better way?
You can create a custom route matcher that uses the appropriate controller.
class LoggedInConstraint < Struct.new(:value)
def matches?(request)
request.cookies.key?("user_token") == value
end
end
match 'reading-list' :to => "reading_list#index", :constraints => LoggedInConstraint.new(true)
match 'reading-list' :to => "session_reading_list#index", :constraints => LoggedInConstraint.new(true)
精彩评论