Pratik lately is doing a great work refactoring ActiveRecord to make a full use of relations. Speaking in code language, this means that in Rails 3 you will be able to do:
User.where(:name => "Jose").order("birthday") |
And it will return a relation. The relation can be further manipulated and the query is only triggered when you call all, first, to_a or some Enumerator method.
Besides that, he’s also doing some crazy experiments, which will probably become a plugin later. While discussing with Pratik some ways to implement equality and inequality, I discovered a neat ruby trick. Open up an irb session and do:
~2 #=> -3 ~42 #=> -43 |
And this method is actually documented.
The nice thing though, is that you can define this method in other classes as well. In the querying scenario for example, we could add this behavior:
class Symbol def ~ :"LOWER(#{self})" end end |
And now we could actually do:
User.where(~:email => "jose@plataformatec.com.br") #=> SELECT * WHERE LOWER(email) = "jose@plataformatec.com.br" |
Unary operators
Yehuda Katz later pointed to me that this can actually be done with any of the three unary operators in Ruby: +, – and ~.
So we could also do:
class String def +@ upcase end def -@ downcase end end |
And now:
+"jose" #=> "JOSE" -"JOSE" #=> "jose" |
You could even “go crazy” and append several unary operators:
+-+"jose" #=> "JOSE" |
And you? Did you know such behavior in Ruby? Do you have any good use case for it?
This entry was posted on Wednesday, December 30th, 2009 at 11:10 am and is filed under English. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.
-
Samuel Flores
-
Samuel Flores
-
http://eustaquiorangel.com TaQ
-
http://eustaquiorangel.com TaQ
-
http://jackndempsey.blogspot.com/ Jack Dempsey
-
http://jackndempsey.blogspot.com Jack Dempsey
-
http://www.joegrossberg.com Joe Grossberg
-
http://www.joegrossberg.com Joe Grossberg
-
http://jstorimer.com Jesse Storimer
-
http://jstorimer.com Jesse Storimer

All
English only
Em português apenas