Path: | doc/virtual_rows.rdoc |
Last Update: | Thu Mar 18 05:47:28 -0600 2010 |
Dataset methods filter, order, and select all take blocks that either yield instances of Sequel::SQL::VirtualRow (if the block takes an argument), or are evaluated in the context of an instance of Sequel::SQL::VirtualRow. These are referred to as virtual row blocks. Many other dataset methods pass the blocks they are given into one of those three methods, so there are actually many Sequel methods that take virtual row blocks.
VirtualRow is a class that returns SQL::Indentifiers, SQL::QualifiedIdentifiers, SQL::Functions, or SQL::WindowFunctions depending on how it is called. This is best shown by example:
ds = DB[:items] ds.filter{column > 1} # column > 1 ds.filter{table__column > 1} # table.column > 1 ds.filter{function(1) > 1} # function(1) > 1 ds.select{version{}} # version() ds.select{count(:*){}} # count(*) ds.select{count(:distinct, col1){}} # count(DISTINCT col1) ds.select{rank(:over){}} # rank() OVER () ds.select{count(:over, :*=>true){}} # count(*) OVER () ds.select{sum(:over, :args=>col1, :partition=>col2, :order=>col3){}} # sum(col1) OVER (PARTITION BY col2 ORDER BY col3)
Basically, the rules are:
If you use a virtual row block that doesn‘t take an argument, the block is instance_evaled, so you can‘t reference methods in the enclosing scope. If you need to call methods of the enclosing scope, you should assign the results to local variables before the block, or just make the block take an argument and use that. If you want to create identifiers or qualified identifiers with the same name as existing local variables, make sure ruby knows it is a method call instead of a local variable reference by not ommiting the parentheses at the end of the method call.