Skip to content

Instantly share code, notes, and snippets.

@benhamill
Created May 17, 2011 18:48
Show Gist options
  • Save benhamill/977095 to your computer and use it in GitHub Desktop.
Save benhamill/977095 to your computer and use it in GitHub Desktop.
Two ways that take a case statement out of your controller.
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
class UserController
def index
@users = user.order(params[:sort_by] || :id)
end
end
@benhamill
Copy link
Author

I am maybe misremembering an example from Jeff Casimir's talk at RailsConf 2011 about moving complexity out of Controllers and into Models (among other, related topics). He presented example_a (as best I can remember) as a better alternative to putting a case statement in your action (which it is). I wondered why the solution wasn't example_b? Maybe because example_a was simplified for example and a real case might be more complex (and have more lines of code in each case option), but maybe example_b is poor for some reason I don't know. Please leave thoughts in the comments.

@benkimball
Copy link

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)

@benkimball
Copy link

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. :)

@benhamill
Copy link
Author

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