Created
May 17, 2011 18:48
-
-
Save benhamill/977095 to your computer and use it in GitHub Desktop.
Two ways that take a case statement out of your controller.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserConroller | |
def index | |
@users = User.sort_by(params[:sort_by]) | |
end | |
end | |
class User | |
def sort_by(sort_by) | |
case sort_by | |
:created_at order(:created_at) | |
:last_updated order(:last_updated) | |
else order(:id) | |
end | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserController | |
def index | |
@users = user.order(params[:sort_by] || :id) | |
end | |
end |
Also: is this a Ruby 1.9 thing? Where are the "when/then" clauses in the case statement? If they are optional I didn't know it. :)
Yeah. I may have fucked up the case syntax. I never use it and was too lazy to look it up. Hopefully it's still clear what the heck I'm blathering about. Your exclusivity point is well made.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well, example B isn't precisely equivalent to A. B allows the end user to sort by anything they like. A allows only created_at, last_updated, or id. (For example: foo.com/users/index?sort_by=nose_length)