What
A collection of handy named_scope
s that you should be able to use in just about any model.
Why
Named scopes turn ugly finders into pretty ones.
Howto
Install the gem from Gemcutter
gem install minty_scopes
Specify the gem dependency in your environment.rb
:
config.gem 'minty_scopes'
In any model, you can get the scopes by extending the module:
class Post < ActiveRecord::Base
extend MintyScopes
end
Scopes
Scopes are grouped into modules by functionality. If you only want some scopes, feel free to extend only the modules you want: extend MintyScopes::Timestamps
Associations
with(:comments) #=> :joins => :comments, :group => 'posts.id' (only posts with comments)
without(:comments) #=> :joins => 'LEFT JOIN comments ON posts.id = comments.post_id',
# :conditions => {'comments.id' => nil}
including(:comments) #=> :include => [:comments]
Except
except(post) #=> [ 'posts.id NOT IN (?)', post ]
except(post, post) #=> [ 'posts.id NOT IN (?)', [post, post] ]
except(post_collection) #=> [ 'posts.id NOT IN (?)', post_collection ]
Order
newest #=> { :order => 'created_at DESC', :limit => per_page || limit }
newest(20) #=> { :order => 'created_at DESC', :limit => 20 }
oldest #=> { :order => 'created_at ASC', :limit => per_page || limit }
oldest(20) #=> { :order => 'created_at ASC', :limit => 20 }
Timestamps
created_on(date) #=> :created_at => (date.beginning_of_day..date.end_of_day)
modified_on(date) #=> :modified_at => (date.beginning_of_day..date.end_of_day)
Thanks
Big thanks to Ryan Daigle for his utility_scopes plugin, the inspiration for this project.
License
The MIT License
Copyright (c) 2009 Dean Strelau, Mint Digital
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.