SlideShare una empresa de Scribd logo
1 de 18
RUBY BLOCKS
AND TEST DRIVEN PERFORMANCE MONITOR (RSPEC 2)
BLOCKS

                 A block is an anonymous function.


my_array.each do |value|
	

 do_something(value)
end
BLOCK SYNTAX
{ |x| puts x}


is the same as:


do |x|
  puts x
end
BLOCKS
                 def dos_veces
                     yield
Yield executes       yield          This is a
   the block     end                 Block!




                         {
                 dos_veces { puts "Hola” }
                 Hola
                 Hola
YIELD WITH PARAMETERS
                                def superpowers
Yield sends its parameters as      a = “x-ray vision”
   arguments to the block          b = “flying”
                                   yield(a, b)
   yield(a,b) sends a and b end
                      to |x, y|

       x is set to a     superpowers do |x,y|
                           puts x,y
       y is set to b     end

                         x-ray vision
                         flying
CHECKING FOR A BLOCK

def repeat(num)
  if block_given?
      num.times { puts yield }
  else
      puts "I can't repeat what you don't tell me"
  end
end
EXPLICIT BLOCK PARAMETER

def repeat_lots(&my_block)
 	

 puts "my_block is a #{my_block.class}"
 	

 puts my_block.call
 	

 puts yield     # this does the same thing
 	

 puts my_block.call
end
PERFORMANCE MONITOR
         EXAMPLE
What do we need to do?
PERFORMANCE MONITOR
         EXAMPLE
How it works:
• Run Code
• Reports How Long it Takes
• Executes Code a Number of Times
• Reports Average Time
TEST DOUBLES
	

   A Test Double replaces the "real" instance of an object used by the production code with
      something suitable for the currently running test, but with the same interface

       •   Stubs

           • Hard-coded values

       •   Mocks

           • Pre-programmed with expectations

           • Fail-fast

           • Test Doubles in general are often called Mock Objects, so be careful about
             terminology

       •   Fakes

           • Can store values across calls, but don't really do what the live object would do

           • E.g. in-memory database
HOW TO TEST CODE WITH
   DEPENDENCIES




        Example from The Rspec Book by
               David Chelimsky
ISOLATING THE SUBJECT




        Example from The Rspec Book by
               David Chelimsky
STUB IN RSPEC

my_instance.stub(:msg).and_return(value)

  MyClass.stub(:msg).and_return(value)
USING STUB FROM IRB

>> require 'rspec/mocks'
>> include RSpec::Mocks::Methods
>>Time.stub(:now).and_return(10,20)
>>Time.now
⇒10
>>Time.now
⇒20
>>Time.now
⇒20



 http://www.ultrasaurus.com/sarahblog/2011/04/repl-rspec-mocks/
USING STUB FROM IRB
>> fake_time = 0
>>Time.stub!(:now).and_return { fake_time += 10 }
>>Time.now
⇒10
>>Time.now
⇒20
>>Time.now
⇒30
STUB IN RSPEC

my_obj.stub(:msg).and_return("1",2)


my_obj.stub(:msg).and_return { ... }
STUB FOR SPECIFIC VALUES

  my_obj.stub(:msg).with(1).and_return(2)
STUB IN RSPEC

my_obj.stub(:msg).and_return { ... }

Más contenido relacionado

La actualidad más candente

ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
Thomas Johnston
 
Small eigen collider
Small eigen colliderSmall eigen collider
Small eigen collider
Andrew Grimm
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
Woody Pewitt
 

La actualidad más candente (20)

ES6 General Introduction
ES6 General IntroductionES6 General Introduction
ES6 General Introduction
 
Small eigen collider
Small eigen colliderSmall eigen collider
Small eigen collider
 
Reactive x
Reactive xReactive x
Reactive x
 
JavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet WetJavaScript from Scratch: Getting Your Feet Wet
JavaScript from Scratch: Getting Your Feet Wet
 
Groovy and Grails talk
Groovy and Grails talkGroovy and Grails talk
Groovy and Grails talk
 
Loops (1)
Loops (1)Loops (1)
Loops (1)
 
CFML Enhancements in ColdFusion 10
CFML Enhancements in ColdFusion 10 CFML Enhancements in ColdFusion 10
CFML Enhancements in ColdFusion 10
 
this is simple
this is simplethis is simple
this is simple
 
A Spin-off: Firebird Checked by PVS-Studio
A Spin-off: Firebird Checked by PVS-StudioA Spin-off: Firebird Checked by PVS-Studio
A Spin-off: Firebird Checked by PVS-Studio
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
 
Objective C Block
Objective C BlockObjective C Block
Objective C Block
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
JavaScript Execution Context
JavaScript Execution ContextJavaScript Execution Context
JavaScript Execution Context
 
IoT Best practices
 IoT Best practices IoT Best practices
IoT Best practices
 
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
 
Monads in Swift
Monads in SwiftMonads in Swift
Monads in Swift
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 
Js interpreter interpreted
Js interpreter interpretedJs interpreter interpreted
Js interpreter interpreted
 
Java Week9(B) Notepad
Java Week9(B)   NotepadJava Week9(B)   Notepad
Java Week9(B) Notepad
 

Destacado (7)

Your first rails app - 2
 Your first rails app - 2 Your first rails app - 2
Your first rails app - 2
 
Form helpers
Form helpersForm helpers
Form helpers
 
What you don't know (yet)
What you don't know (yet)What you don't know (yet)
What you don't know (yet)
 
Climogramas mundiales
Climogramas mundialesClimogramas mundiales
Climogramas mundiales
 
Extending rails
Extending railsExtending rails
Extending rails
 
Religion and Sustainable Development in China
Religion and Sustainable Development in ChinaReligion and Sustainable Development in China
Religion and Sustainable Development in China
 
China’s Development Pattern as found in its Sacred Literature
China’s Development Pattern as found in its Sacred LiteratureChina’s Development Pattern as found in its Sacred Literature
China’s Development Pattern as found in its Sacred Literature
 

Similar a Ruby Blocks

JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
tobiascrawley
 

Similar a Ruby Blocks (20)

Ruby Blocks
Ruby BlocksRuby Blocks
Ruby Blocks
 
Spock
SpockSpock
Spock
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Functional Programming with JavaScript
Functional Programming with JavaScriptFunctional Programming with JavaScript
Functional Programming with JavaScript
 
Concurrency at the Database Layer
Concurrency at the Database Layer Concurrency at the Database Layer
Concurrency at the Database Layer
 
Spock: Test Well and Prosper
Spock: Test Well and ProsperSpock: Test Well and Prosper
Spock: Test Well and Prosper
 
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und GebBDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
BDD - Behavior Driven Development Webapps mit Groovy Spock und Geb
 
Clojure And Swing
Clojure And SwingClojure And Swing
Clojure And Swing
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JRuby e DSL
JRuby e DSLJRuby e DSL
JRuby e DSL
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
 
JavaScript Looping Statements
JavaScript Looping StatementsJavaScript Looping Statements
JavaScript Looping Statements
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
 
Torquebox OSCON Java 2011
Torquebox OSCON Java 2011Torquebox OSCON Java 2011
Torquebox OSCON Java 2011
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
Ruby Blocks
Ruby BlocksRuby Blocks
Ruby Blocks
 

Más de Blazing Cloud

RSpec Quick Reference
RSpec Quick ReferenceRSpec Quick Reference
RSpec Quick Reference
Blazing Cloud
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
Blazing Cloud
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
Blazing Cloud
 

Más de Blazing Cloud (20)

Rails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyRails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_many
 
Active Record Introduction - 3
Active Record Introduction - 3Active Record Introduction - 3
Active Record Introduction - 3
 
Rails Class Intro - 1
Rails Class Intro - 1 Rails Class Intro - 1
Rails Class Intro - 1
 
RSpec Quick Reference
RSpec Quick ReferenceRSpec Quick Reference
RSpec Quick Reference
 
2day Ruby Class Intro
2day Ruby Class Intro2day Ruby Class Intro
2day Ruby Class Intro
 
Mobile Lean UX
Mobile Lean UXMobile Lean UX
Mobile Lean UX
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
 
Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3
 
Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)
 
Introduction to Rails
Introduction to RailsIntroduction to Rails
Introduction to Rails
 
ActiveRecord
ActiveRecordActiveRecord
ActiveRecord
 
Ruby on Rails Class intro
Ruby on Rails Class introRuby on Rails Class intro
Ruby on Rails Class intro
 
Ruby on rails toolbox
Ruby on rails toolboxRuby on rails toolbox
Ruby on rails toolbox
 
Routes Controllers
Routes ControllersRoutes Controllers
Routes Controllers
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Active Record
Active RecordActive Record
Active Record
 
Enumerables
EnumerablesEnumerables
Enumerables
 
Reg EX
Reg EXReg EX
Reg EX
 
Files IO
Files IOFiles IO
Files IO
 
Power Ruby
Power RubyPower Ruby
Power Ruby
 

Último

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 

Ruby Blocks

  • 1. RUBY BLOCKS AND TEST DRIVEN PERFORMANCE MONITOR (RSPEC 2)
  • 2. BLOCKS A block is an anonymous function. my_array.each do |value| do_something(value) end
  • 3. BLOCK SYNTAX { |x| puts x} is the same as: do |x| puts x end
  • 4. BLOCKS def dos_veces yield Yield executes yield This is a the block end Block! { dos_veces { puts "Hola” } Hola Hola
  • 5. YIELD WITH PARAMETERS def superpowers Yield sends its parameters as a = “x-ray vision” arguments to the block b = “flying” yield(a, b) yield(a,b) sends a and b end to |x, y| x is set to a superpowers do |x,y| puts x,y y is set to b end x-ray vision flying
  • 6. CHECKING FOR A BLOCK def repeat(num) if block_given? num.times { puts yield } else puts "I can't repeat what you don't tell me" end end
  • 7. EXPLICIT BLOCK PARAMETER def repeat_lots(&my_block) puts "my_block is a #{my_block.class}" puts my_block.call puts yield # this does the same thing puts my_block.call end
  • 8. PERFORMANCE MONITOR EXAMPLE What do we need to do?
  • 9. PERFORMANCE MONITOR EXAMPLE How it works: • Run Code • Reports How Long it Takes • Executes Code a Number of Times • Reports Average Time
  • 10. TEST DOUBLES A Test Double replaces the "real" instance of an object used by the production code with something suitable for the currently running test, but with the same interface • Stubs • Hard-coded values • Mocks • Pre-programmed with expectations • Fail-fast • Test Doubles in general are often called Mock Objects, so be careful about terminology • Fakes • Can store values across calls, but don't really do what the live object would do • E.g. in-memory database
  • 11. HOW TO TEST CODE WITH DEPENDENCIES Example from The Rspec Book by David Chelimsky
  • 12. ISOLATING THE SUBJECT Example from The Rspec Book by David Chelimsky
  • 13. STUB IN RSPEC my_instance.stub(:msg).and_return(value) MyClass.stub(:msg).and_return(value)
  • 14. USING STUB FROM IRB >> require 'rspec/mocks' >> include RSpec::Mocks::Methods >>Time.stub(:now).and_return(10,20) >>Time.now ⇒10 >>Time.now ⇒20 >>Time.now ⇒20 http://www.ultrasaurus.com/sarahblog/2011/04/repl-rspec-mocks/
  • 15. USING STUB FROM IRB >> fake_time = 0 >>Time.stub!(:now).and_return { fake_time += 10 } >>Time.now ⇒10 >>Time.now ⇒20 >>Time.now ⇒30
  • 17. STUB FOR SPECIFIC VALUES my_obj.stub(:msg).with(1).and_return(2)

Notas del editor

  1. \n
  2. \n
  3. two ways to declare a block\nuse curly brackets for single lines of code\nuse do end for multi lines of code\n
  4. What is a block? \nIt is the ability to take a block of code, wrap it up in an object and pass it to a method. \nThen you can run the block of code within the method any time you want…sometimes twice! \nThe result is kind of like sending a method to a method, except that a block isn’t bound to an object like a method is – it is an object. \nSo what? Why use blocks?\nelegant syntax for iterators\nBecause there are some things that only blocks can do, like being passed to a method and being returned by a method.\n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n