order(:title => :asc, :year => :desc)

23 views
Skip to first unread message

Janko Marohnić

unread,
Mar 23, 2015, 8:13:40 PM3/23/15
to seque...@googlegroups.com
Hi Jeremy (again :)),

ActiveRecord 4 (I think) added a nice improvement to the ordering syntax:

Movie.order(:title => :asc, :year => :desc)

I really like this syntax, because it's natural to use and very readable. While I'm happy that Sequel has so many different ways of writing queries, I still wasn't quite happy with ordering. I find `Sequel.desc(:year)` slighly verbose. `:year.desc` reads really nice, though, but you have to include core_extensions for that.

I feel like ordering is common enough to deserve a more fluent syntax. If you think this syntax would be cool as well, I'd gladly make a pull request :)

Jeremy Evans

unread,
Mar 23, 2015, 8:57:59 PM3/23/15
to seque...@googlegroups.com
This can't be used in the core as it breaks backwards compatibility and violates the general rule in Sequel that hashes are used for expressions.  Currently your code is valid Sequel and results in:

  SELECT * FROM movies ORDER BY ((title = asc) AND (year = desc))

Ordering on boolean expressions is supported on most SQL databases, where false generally sorts before true.

A simpler solution to what you want in Sequel is to use a virtual row block:

  Movie.order{[:title, year.desc]}

Note that on ruby 2.0+, you can use the core_refinements extension to enable :year.desc to work in a given file without it having a global effect.

If you wanted to support the ActiveRecord syntax, you'd have to add a new method for it, or you have to add it as an extension that overrode order and related methods to add special handling for hash arguments.  Because of the ease of doing this with virtual row blocks, I think it would be better to do this as an external library instead of included with Sequel.

Thanks,
Jeremy

Janko Marohnić

unread,
Mar 23, 2015, 9:09:14 PM3/23/15
to seque...@googlegroups.com
Cool, I didn't know that I can call desc/asc in virtual rows. Now when I think about it, "year" is simply a Sequel expression, which I remember before that it has defined desc/asc methods. The ActiveRecord syntax is really not needed then. Thank you for your help again!

--
You received this message because you are subscribed to a topic in the Google Groups "sequel-talk" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/sequel-talk/-wtNzTWRHuU/unsubscribe.
To unsubscribe from this group and all its topics, send an email to sequel-talk...@googlegroups.com.
To post to this group, send email to seque...@googlegroups.com.
Visit this group at http://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages