3. What can be scoped?
Routes, ModelsModels, Rake Tasks
Implementation from Description
ActionDispatch
::Routing::Mapper::Scoping
scope(*args) { || ... }
Scopes a set of routes to the given default options.
ActiveRecord
::Associations::CollectionProxy
Scope()
Returns a Relation object for the records in this
association
ActiveRecord
::DeprecatedFinders
scope(name, body = {}, &block)
ActiveRecord
::Reflection::MacroReflection#sco
pe
ActiveRecord
::Scoping::Named::ClassMethods
scope(name, body, &block)
Rake::Task#scope Array of nested namespaces names used for task
lookup by this task.
4. Scoping Models, Part 1
From ActiveRecord::Scoping::Named::ClassMethods
“scope” adds a class method for retrieving and
querying objects: it's a way to narrow a database
query.
def scope(name, body, &block)
extension = Module.new(&block) if block
singleton_class.send(:define_method, name) do |*args|
scope = all.scoping { body.call(*args) }
scope = scope.extending(extension) if extension
scope || all
end
end
5. Scoping Models, Part 2
● Scopes are simply 'syntactic sugar' for defining
a class method.
This:
Same as:
SQL:
scope :tabby, -> { where(coat_coloration: 'tabby') }
def self.tabby
where(coat_coloration: 'tabby')
end
SELECT “cats”.* FROM “cats” WHERE “cats”.”coat_coloration” = “tabby”;
6. Taking advantage
Cat.tabby.first Cat.tabby.kitten
Cat.tabby.count Cat.kitten.tabby.count
Cat.tabby.each(&block)
The object returned by calling a scope on its
class resembles the object constructed by a
has_many declaration.
These methods are also available to
has_many associations.
cat_palace.cats.tabby.first cat_palace.cats.tabby.kitten
cat_palace.cats.tabby.count cat_palace.cats.kitten.tabby.count
cat_palace.cats.tabby.each(&block)
7. gem 'has_scope'
Maps controller filters to resource scopes
# Define scope in model
# Use as filters by declaring has_scope in controller and apply scopes to a
resource by calling apply_scopes
# Send request for LOLcats
class Cat < ActiveRecord::Base
scope :LOL, -> { where(funny: true) }
end
class CatsController < ApplicationController
has_scope :LOL, type: :boolean
def index
@cats = apply_scopes(Cat).all
end
end
/cats?LOL=true
8. Yes, model catYes, model cat
can haz scope.can haz scope.http://www.flickr.com/photos/35445050@N00/6218860576/