Module: BasicNamedScopes
- Defined in:
- lib/basic_named_scopes.rb
Overview
Basic named scopes for ActiveRecord. Propagates the parameters of the find-method as named scopes, for easy reusability and prettier code.
Instead of writing:
Post.all(:conditions => { :published => true }, :select => :title, :include => :author)
You can now write:
Post.conditions(:published => true).select(:title).with(:author)
All named scopes are called the same, except for include
, which is now called with
, because include
is a reserved method.
Also, the scope conditions
is aliased as where
, just as in ActiveRecord 3.
Reuse them by making class methods:
class Post < ActiveRecord::Base
def self.published
conditions(:published => true)
end
def self.visible
conditions(:visible => true)
end
def self.index
published.visible
end
end
Also, the all
-method is a named scope now, so you can chain after callling all, for greater flexibility.
Post.all.published
Arrays can be used as multple parameters too, sparing you some brackets.
Post.with(:author, :comments).conditions("name LIKE ?", query)
The read_only
and lock
scopes default to true, but can be adjusted.
Post.readonly # => same as Post.all(:readonly => true)
Post.readonly(false) # => same as Post.all(:readonly => false)
Constant Summary collapse
- FIND_PARAMETERS =
These are the normal parameters that will be turned into named scopes.
[:conditions, :order, :group, :having, :limit, :offset, :joins, :select, :from]
- FIND_ALIASES =
These are aliased parameters. The keys are scope names, the values are the option they represent.
{ :where => :conditions, :with => :include, :includes => :include, :sel => :select }
- FIND_BOOLEAN_SWITCHES =
These are the parameters that want a boolean.
[:readonly, :lock]
Class Method Summary collapse
- .apply_basic_named_scopes(model) ⇒ Object
-
.extended(model) ⇒ Object
When you extend an ActiveRecord model (or Base for that matter) it will add the named scopes.
Class Method Details
.apply_basic_named_scopes(model) ⇒ Object
69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/basic_named_scopes.rb', line 69 def apply_basic_named_scopes(model) FIND_PARAMETERS.each do |parameter| model.named_scope(parameter, (parameter)) end FIND_ALIASES.each do |name, parameter| model.named_scope(name, (parameter)) end FIND_BOOLEAN_SWITCHES.each do |parameter| model.named_scope(parameter, default_to_true(parameter)) end model.named_scope(:all, default_to_empty_hash) end |
.extended(model) ⇒ Object
When you extend an ActiveRecord model (or Base for that matter) it will add the named scopes. This will automatically be done when the gem is loaded.
65 66 67 |
# File 'lib/basic_named_scopes.rb', line 65 def extended(model) apply_basic_named_scopes(model) end |