SlideShare a Scribd company logo
1 of 9
Download to read offline
Model catModel cat
Ellen Musick
Can Haz Scope?Can Haz Scope?
http://www.flickr.com/photos/35445050@N00/6218860576/
What scope?
● I'm not talking about variable scope.
● $ ri scope
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.
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
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”;
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)
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
Yes, model catYes, model cat
can haz scope.can haz scope.http://www.flickr.com/photos/35445050@N00/6218860576/
Resources
● $ ri scope
● http://api.rubyonrails.org/classes/ActiveRecord/Scopi
ng/Named/ClassMethods.html#method-i-scope
● https://github.com/rails/rails/blob/master/activerecord
/lib/active_record/scoping/named.rb
● http://guides.rubyonrails.org/active_record_querying.
html#scopes
● https://github.com/plataformatec/has_scope

More Related Content

What's hot

Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScriptinjulkarnilesh
 
First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)Wildan Maulana
 
OCamlOScope: a New OCaml API Search
OCamlOScope: a New OCaml API SearchOCamlOScope: a New OCaml API Search
OCamlOScope: a New OCaml API SearchJun Furuse
 
Session 15 - Collections - Array List
Session 15 - Collections - Array ListSession 15 - Collections - Array List
Session 15 - Collections - Array ListPawanMM
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議dico_leque
 
Interface record comparator
Interface record comparatorInterface record comparator
Interface record comparatormyrajendra
 
The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210Mahmoud Samir Fayed
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio
 
القوائم المترابطة Linked List باستخدام لغة جافا
القوائم المترابطة Linked List باستخدام لغة جافاالقوائم المترابطة Linked List باستخدام لغة جافا
القوائم المترابطة Linked List باستخدام لغة جافاMahmoud Alfarra
 
ActiveRecord Query Interface
ActiveRecord Query InterfaceActiveRecord Query Interface
ActiveRecord Query Interfacemrsellars
 
Active records before_type_cast
Active records before_type_castActive records before_type_cast
Active records before_type_castthehoagie
 
2 introduction to data structure
2  introduction to data structure2  introduction to data structure
2 introduction to data structureMahmoud Alfarra
 

What's hot (20)

Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)First Steps. (db4o - Object Oriented Database)
First Steps. (db4o - Object Oriented Database)
 
OCamlOScope: a New OCaml API Search
OCamlOScope: a New OCaml API SearchOCamlOScope: a New OCaml API Search
OCamlOScope: a New OCaml API Search
 
7 stack and vector
7 stack and vector7 stack and vector
7 stack and vector
 
Session 15 - Collections - Array List
Session 15 - Collections - Array ListSession 15 - Collections - Array List
Session 15 - Collections - Array List
 
Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議Meta-objective Lisp @名古屋 Reject 会議
Meta-objective Lisp @名古屋 Reject 会議
 
Pune Clojure Course Outline
Pune Clojure Course OutlinePune Clojure Course Outline
Pune Clojure Course Outline
 
Hello scala
Hello scalaHello scala
Hello scala
 
Interface record comparator
Interface record comparatorInterface record comparator
Interface record comparator
 
Python for lab_folk
Python for lab_folkPython for lab_folk
Python for lab_folk
 
The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210The Ring programming language version 1.9 book - Part 90 of 210
The Ring programming language version 1.9 book - Part 90 of 210
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Luis Atencio on RxJS
Luis Atencio on RxJSLuis Atencio on RxJS
Luis Atencio on RxJS
 
القوائم المترابطة Linked List باستخدام لغة جافا
القوائم المترابطة Linked List باستخدام لغة جافاالقوائم المترابطة Linked List باستخدام لغة جافا
القوائم المترابطة Linked List باستخدام لغة جافا
 
Stack Data structure
Stack Data structureStack Data structure
Stack Data structure
 
ActiveRecord Query Interface
ActiveRecord Query InterfaceActiveRecord Query Interface
ActiveRecord Query Interface
 
Active records before_type_cast
Active records before_type_castActive records before_type_cast
Active records before_type_cast
 
2 introduction to data structure
2  introduction to data structure2  introduction to data structure
2 introduction to data structure
 
Meet scala
Meet scalaMeet scala
Meet scala
 
Advanced R cheat sheet
Advanced R cheat sheetAdvanced R cheat sheet
Advanced R cheat sheet
 

Similar to Lightening Talk: Model Cat Can Haz Scope?

C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsMayank Jain
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Framework prototype
Framework prototypeFramework prototype
Framework prototypeDevMix
 
Object and class in java
Object and class in javaObject and class in java
Object and class in javaUmamaheshwariv1
 
Identifier namespaces in mathematical notation
Identifier namespaces in mathematical notationIdentifier namespaces in mathematical notation
Identifier namespaces in mathematical notationAlexey Grigorev
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.pptaasuran
 
Sonar rules in action with walkmod
Sonar rules in action with walkmodSonar rules in action with walkmod
Sonar rules in action with walkmodRaquel Pau
 
Core java concepts
Core java  conceptsCore java  concepts
Core java conceptsRam132
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directivesGreg Bergé
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1Jano Suchal
 

Similar to Lightening Talk: Model Cat Can Haz Scope? (20)

How to write Ruby extensions with Crystal
How to write Ruby extensions with CrystalHow to write Ruby extensions with Crystal
How to write Ruby extensions with Crystal
 
Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
Java
JavaJava
Java
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Java02
Java02Java02
Java02
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Framework prototype
Framework prototypeFramework prototype
Framework prototype
 
Object and class in java
Object and class in javaObject and class in java
Object and class in java
 
Identifier namespaces in mathematical notation
Identifier namespaces in mathematical notationIdentifier namespaces in mathematical notation
Identifier namespaces in mathematical notation
 
C++ Classes Tutorials.ppt
C++ Classes Tutorials.pptC++ Classes Tutorials.ppt
C++ Classes Tutorials.ppt
 
C++ classes
C++ classesC++ classes
C++ classes
 
Java
JavaJava
Java
 
Sonar rules in action with walkmod
Sonar rules in action with walkmodSonar rules in action with walkmod
Sonar rules in action with walkmod
 
Core java concepts
Core java  conceptsCore java  concepts
Core java concepts
 
C++ classes
C++ classesC++ classes
C++ classes
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Extend GraphQL with directives
Extend GraphQL with directivesExtend GraphQL with directives
Extend GraphQL with directives
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 

Recently uploaded

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Recently uploaded (20)

CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 

Lightening Talk: Model Cat Can Haz Scope?

  • 1. Model catModel cat Ellen Musick Can Haz Scope?Can Haz Scope? http://www.flickr.com/photos/35445050@N00/6218860576/
  • 2. What scope? ● I'm not talking about variable scope. ● $ ri scope
  • 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/
  • 9. Resources ● $ ri scope ● http://api.rubyonrails.org/classes/ActiveRecord/Scopi ng/Named/ClassMethods.html#method-i-scope ● https://github.com/rails/rails/blob/master/activerecord /lib/active_record/scoping/named.rb ● http://guides.rubyonrails.org/active_record_querying. html#scopes ● https://github.com/plataformatec/has_scope