mutsuda/Invoicer — comment on commit 3a7ee069310977032fd7e800f8c21c046ab9647b
File: app/controllers/invoices_controller.rb line 8
By albertbellonch:

I would rather move this into the Model by using a lambda scope ([more info here](http://api.rubyonrails.org/classes/ActiveRecord/NamedScope/ClassMethods.html#method-i-scope)). Scopes are just like views in a database: subsets of the whole entries for a specific model. You may have them as a method, or as a scope (which is more clear, at least for me).

So, go to the Invoice model and add:
```scope :for_year, lambda { |year| where('date >= ?', Date.new(year)).where('date < ?', Date.new(year) + 1.year) }
```

Note that:

* A lambda scope is a special scope which accepts one or more parameters.
* You can concatenate some operations on the base ```Invoice.all``` in order to prune the data and get your results.
* Date.new(a_year) returns the first day of that year.

Then, you can use this in your controller by simply doing:
```class InvoicesController < ApplicationController
...
def index
@invoices = (year = params[:year]) ? Invoice.for_year(year) : Invoice.all
end
end
```

Note here we have a clever and tricky code line in InvoicesController#index

* If params[:year] exist, save it into a variable named "year", and set the result of Invoice.for_year(year) to @invoices.
* Otherwise, set all the invoices to @invoices.