title: ruby on rails named scope implementation
body: <p>From the book Agile Web Development With Rails</p>
  
  <pre><code>class Order &lt; ActiveRecord::Base
     named_scope :last_n_days, lambda { |days| {:conditions =&gt;
        ['updated &lt; ?' , days] } }
  
     named_scope :checks, :conditions =&gt; {:pay_type =&gt; :check}
  end
  </code></pre>
  
  <p>The statement</p>
  
  <pre><code>orders = Orders.checks.last_n_days(7)
  </code></pre>
  
  <p>will result to only one query to the database.</p>
  
  <p>How does rails implement this? I'm new to Ruby and I'm wondering if there's a special construct that allows this to happen.</p>
  
  <p>To be able to chain methods like that, the functions generated by named_scope must be returning themselves or an object than can be scoped further. But how does Ruby know that it is the last function call and that it should query the database now?</p>
  
  <p>I ask this because the statement above actually queries the database and not just returns an SQL statement that results from chaining.</p>