SlideShare uma empresa Scribd logo
1 de 17
Baixar para ler offline
Weird 
Ruby
Scott Smith 
· https://github.com/oldfartdeveloper 
· Twitter @ofd 
· Blog http://blog.scottnelsonsmith.com 
Co-run 
· OC-Ruby 
· Ember-SC
Rack Attack · A Gem: rackattack 
· Ruby expressions I've never seen before
Can you tell me what they mean? Here goes!
Operator Method 
with arguments
module Rack 
class Attack 
class Check 
attr_reader :name, :block, :type 
def initialize(name, options = {}, block) 
@name, @block = name, block 
@type = options.fetch(:type, nil) 
end 
# Wha'? What's this do? 
def [](req) 
block[req].tap {|match| 
if match 
req.env["rack.attack.matched"] = name 
req.env["rack.attack.match_type"] = type 
Rack::Attack.instrument(req) 
end 
} 
end 
end 
end 
end
"or" and "," 
operators 
· Precedences? 
· Parenthesis (or lack of them)
module Rack 
class Attack 
class Fail2Ban 
class << self 
def filter(discriminator, options) 
# Wha? What's happening here? 
bantime = options[:bantime] or raise ArgumentError, "Must pass bantime option" 
findtime = options[:findtime] or raise ArgumentError, "Must pass findtime option" 
maxretry = options[:maxretry] or raise ArgumentError, "Must pass maxretry option" 
...
Don' Do 
Nuttin'
module Rack 
class Attack 
class Request < ::Rack::Request 
end 
end 
end
instance or 
class var?
class Rack::Attack 
... 
class << self 
# Wha? These instance or class accessors? 
attr_accessor :notifier, :blacklisted_response, :throttled_response 
def whitelist(name, &block) 
self.whitelists[name] = Whitelist.new(name, block) 
end 
... 
# Wha? Is @whitelists an instance or class var? 
def whitelists; @whitelists ||= {}; end 
... 
end 
...
Is it 
instance 
or class 
method?
Within Rack::Attack we have this instance 
method 
def call(env) 
req = Rack::Attack::Request.new(env) 
# Wha? Is #whitelisted? an instance or class method? 
if whitelisted?(req) 
@app.call(env) 
elsif blacklisted?(req) 
self.class.blacklisted_response[env] 
elsif throttled?(req) 
self.class.throttled_response[env] 
else 
tracked?(req) 
@app.call(env) 
end 
end
Nudity In a class but not in a method
class Rack::Attack 
# Wha? 
throttle('req/ip', 
:limit => (ENV['RACKATTACK_LIMIT'].present? ? Integer(ENV['RACKATTACK_LIMIT']) : 300), 
:period => (ENV['RACKATTACK_PERIOD'].present? ? Integer(ENV['RACKATTACK_PERIOD']) : 1.minutes)) do |req| 
req.ip 
end 
whitelist('from hedgeye office') do |req| 
if (whitelist_pattern = ENV['WHITELIST_IP_PATTERN']) && !whitelist_pattern.blank? 
Rails.logger.info("#{req.ip} =~ /#{whitelist_pattern}/ #=> #{req.ip =~ /#{whitelist_pattern}/}") 
req.ip =~ /#{whitelist_pattern}/ 
end 
end 
# https://www.pivotaltracker.com/n/projects/414867/stories/76620326 
blacklist('block bad user agent request from Chinese bot') do |req| 
offset = req.user_agent =~ /WEasouSpiderW/ 
!offset.nil? && offset >= 0 
end 
self.throttled_response = lambda do |env| 
[ 503, # status 
{}, # headers 
['']] # body end 
end 
end
SCORE 
7 out of 7 - god 
otherwise: mortal 
Thanks for playing

Mais conteúdo relacionado

Mais procurados

Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
Todor Kolev
 
Exception Handling1
Exception Handling1Exception Handling1
Exception Handling1
guest739536
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming Patterns
Vasil Remeniuk
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
Shahjahan Samoon
 

Mais procurados (20)

Java script unleashed
Java script unleashedJava script unleashed
Java script unleashed
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Functional Java 8 - Introduction
Functional Java 8 - IntroductionFunctional Java 8 - Introduction
Functional Java 8 - Introduction
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
Java findamentals1
Java findamentals1Java findamentals1
Java findamentals1
 
DIY: Analyse statique en Java
DIY: Analyse statique en JavaDIY: Analyse statique en Java
DIY: Analyse statique en Java
 
Scala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgrammingScala Reflection & Runtime MetaProgramming
Scala Reflection & Runtime MetaProgramming
 
Ponies and Unicorns With Scala
Ponies and Unicorns With ScalaPonies and Unicorns With Scala
Ponies and Unicorns With Scala
 
Clean Code (why not do it)
Clean Code (why not do it)Clean Code (why not do it)
Clean Code (why not do it)
 
Core Java
Core JavaCore Java
Core Java
 
Exception Handling1
Exception Handling1Exception Handling1
Exception Handling1
 
Effective Scala: Programming Patterns
Effective Scala: Programming PatternsEffective Scala: Programming Patterns
Effective Scala: Programming Patterns
 
1 the language essentials
1 the language essentials1 the language essentials
1 the language essentials
 
String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
Introduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogicIntroduction to Type Script by Sam Goldman, SmartLogic
Introduction to Type Script by Sam Goldman, SmartLogic
 
Introduction to Dart
Introduction to DartIntroduction to Dart
Introduction to Dart
 
Ruby 3の型解析に向けた計画
Ruby 3の型解析に向けた計画Ruby 3の型解析に向けた計画
Ruby 3の型解析に向けた計画
 
Java Performance MythBusters
Java Performance MythBustersJava Performance MythBusters
Java Performance MythBusters
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 

Destaque

Lattelecom Optiskais internets
Lattelecom Optiskais internetsLattelecom Optiskais internets
Lattelecom Optiskais internets
EuroRSCGRiga
 
Lattelecom Optiskais internets RUS
Lattelecom Optiskais internets RUSLattelecom Optiskais internets RUS
Lattelecom Optiskais internets RUS
EuroRSCGRiga
 
Sales Presentation v1 copy
Sales Presentation v1 copySales Presentation v1 copy
Sales Presentation v1 copy
Eddie Twomey
 
Current Eddie_Twomey C.V. 2015
Current Eddie_Twomey C.V. 2015Current Eddie_Twomey C.V. 2015
Current Eddie_Twomey C.V. 2015
Eddie Twomey
 

Destaque (14)

Lattelecom Optiskais internets
Lattelecom Optiskais internetsLattelecom Optiskais internets
Lattelecom Optiskais internets
 
Rock Paper Scissors Multiplayer Website in Elixir and Elm
Rock Paper Scissors Multiplayer Website in Elixir and ElmRock Paper Scissors Multiplayer Website in Elixir and Elm
Rock Paper Scissors Multiplayer Website in Elixir and Elm
 
Lattelecom Optiskais internets RUS
Lattelecom Optiskais internets RUSLattelecom Optiskais internets RUS
Lattelecom Optiskais internets RUS
 
RFK - Leader
RFK - LeaderRFK - Leader
RFK - Leader
 
Sales Presentation v1 copy
Sales Presentation v1 copySales Presentation v1 copy
Sales Presentation v1 copy
 
Sales presentation - Fastway Couriers
Sales presentation - Fastway CouriersSales presentation - Fastway Couriers
Sales presentation - Fastway Couriers
 
Say yes to a meatless monday
Say yes to a meatless mondaySay yes to a meatless monday
Say yes to a meatless monday
 
Training Delivery Options
Training Delivery OptionsTraining Delivery Options
Training Delivery Options
 
What About Elm?
What About Elm?What About Elm?
What About Elm?
 
Stress powerpointbasic
Stress powerpointbasicStress powerpointbasic
Stress powerpointbasic
 
What is a Ceph (and why do I care). OpenStack storage - Colorado OpenStack Me...
What is a Ceph (and why do I care). OpenStack storage - Colorado OpenStack Me...What is a Ceph (and why do I care). OpenStack storage - Colorado OpenStack Me...
What is a Ceph (and why do I care). OpenStack storage - Colorado OpenStack Me...
 
Current Eddie_Twomey C.V. 2015
Current Eddie_Twomey C.V. 2015Current Eddie_Twomey C.V. 2015
Current Eddie_Twomey C.V. 2015
 
Facebook Ads
Facebook AdsFacebook Ads
Facebook Ads
 
Limites Problemas resueltos
Limites Problemas resueltosLimites Problemas resueltos
Limites Problemas resueltos
 

Semelhante a Weird Ruby

Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
ConFoo
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
Jano Suchal
 

Semelhante a Weird Ruby (20)

Ruby, muito mais que reflexivo
Ruby, muito mais que reflexivoRuby, muito mais que reflexivo
Ruby, muito mais que reflexivo
 
Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)Lisp Macros in 20 Minutes (Featuring Clojure)
Lisp Macros in 20 Minutes (Featuring Clojure)
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
All I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web FrameworkAll I Need to Know I Learned by Writing My Own Web Framework
All I Need to Know I Learned by Writing My Own Web Framework
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Metaprogramming
MetaprogrammingMetaprogramming
Metaprogramming
 
Mutation testing with the mutant gem
Mutation testing with the mutant gemMutation testing with the mutant gem
Mutation testing with the mutant gem
 
Python magicmethods
Python magicmethodsPython magicmethods
Python magicmethods
 
Metaprogramovanie #1
Metaprogramovanie #1Metaprogramovanie #1
Metaprogramovanie #1
 
Ruby tricks2
Ruby tricks2Ruby tricks2
Ruby tricks2
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
An excuse to Try, Either, folding, and Future. sequence
An excuse to Try, Either, folding, and Future. sequenceAn excuse to Try, Either, folding, and Future. sequence
An excuse to Try, Either, folding, and Future. sequence
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Advanced Python, Part 1
Advanced Python, Part 1Advanced Python, Part 1
Advanced Python, Part 1
 
What You Need to Know about Lambdas
What You Need to Know about LambdasWhat You Need to Know about Lambdas
What You Need to Know about Lambdas
 

Último

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
masabamasaba
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Último (20)

Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 

Weird Ruby

  • 2. Scott Smith · https://github.com/oldfartdeveloper · Twitter @ofd · Blog http://blog.scottnelsonsmith.com Co-run · OC-Ruby · Ember-SC
  • 3. Rack Attack · A Gem: rackattack · Ruby expressions I've never seen before
  • 4. Can you tell me what they mean? Here goes!
  • 6. module Rack class Attack class Check attr_reader :name, :block, :type def initialize(name, options = {}, block) @name, @block = name, block @type = options.fetch(:type, nil) end # Wha'? What's this do? def [](req) block[req].tap {|match| if match req.env["rack.attack.matched"] = name req.env["rack.attack.match_type"] = type Rack::Attack.instrument(req) end } end end end end
  • 7. "or" and "," operators · Precedences? · Parenthesis (or lack of them)
  • 8. module Rack class Attack class Fail2Ban class << self def filter(discriminator, options) # Wha? What's happening here? bantime = options[:bantime] or raise ArgumentError, "Must pass bantime option" findtime = options[:findtime] or raise ArgumentError, "Must pass findtime option" maxretry = options[:maxretry] or raise ArgumentError, "Must pass maxretry option" ...
  • 10. module Rack class Attack class Request < ::Rack::Request end end end
  • 12. class Rack::Attack ... class << self # Wha? These instance or class accessors? attr_accessor :notifier, :blacklisted_response, :throttled_response def whitelist(name, &block) self.whitelists[name] = Whitelist.new(name, block) end ... # Wha? Is @whitelists an instance or class var? def whitelists; @whitelists ||= {}; end ... end ...
  • 13. Is it instance or class method?
  • 14. Within Rack::Attack we have this instance method def call(env) req = Rack::Attack::Request.new(env) # Wha? Is #whitelisted? an instance or class method? if whitelisted?(req) @app.call(env) elsif blacklisted?(req) self.class.blacklisted_response[env] elsif throttled?(req) self.class.throttled_response[env] else tracked?(req) @app.call(env) end end
  • 15. Nudity In a class but not in a method
  • 16. class Rack::Attack # Wha? throttle('req/ip', :limit => (ENV['RACKATTACK_LIMIT'].present? ? Integer(ENV['RACKATTACK_LIMIT']) : 300), :period => (ENV['RACKATTACK_PERIOD'].present? ? Integer(ENV['RACKATTACK_PERIOD']) : 1.minutes)) do |req| req.ip end whitelist('from hedgeye office') do |req| if (whitelist_pattern = ENV['WHITELIST_IP_PATTERN']) && !whitelist_pattern.blank? Rails.logger.info("#{req.ip} =~ /#{whitelist_pattern}/ #=> #{req.ip =~ /#{whitelist_pattern}/}") req.ip =~ /#{whitelist_pattern}/ end end # https://www.pivotaltracker.com/n/projects/414867/stories/76620326 blacklist('block bad user agent request from Chinese bot') do |req| offset = req.user_agent =~ /WEasouSpiderW/ !offset.nil? && offset >= 0 end self.throttled_response = lambda do |env| [ 503, # status {}, # headers ['']] # body end end end
  • 17. SCORE 7 out of 7 - god otherwise: mortal Thanks for playing