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

JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
Max Lee
 

Último (20)

Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdfMicrosoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
Microsoft 365 Copilot; An AI tool changing the world of work _PDF.pdf
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdfStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi.pdf
 
Sourcing Success - How to Find a Clothing Manufacturer
Sourcing Success - How to Find a Clothing ManufacturerSourcing Success - How to Find a Clothing Manufacturer
Sourcing Success - How to Find a Clothing Manufacturer
 
Weeding your micro service landscape.pdf
Weeding your micro service landscape.pdfWeeding your micro service landscape.pdf
Weeding your micro service landscape.pdf
 
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
Tree in the Forest - Managing Details in BDD Scenarios (live2test 2024)
 
Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdfImplementing KPIs and Right Metrics for Agile Delivery Teams.pdf
Implementing KPIs and Right Metrics for Agile Delivery Teams.pdf
 
Microsoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdfMicrosoft365_Dev_Security_2024_05_16.pdf
Microsoft365_Dev_Security_2024_05_16.pdf
 
IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024IT Software Development Resume, Vaibhav jha 2024
IT Software Development Resume, Vaibhav jha 2024
 
Community is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea GouletCommunity is Just as Important as Code by Andrea Goulet
Community is Just as Important as Code by Andrea Goulet
 
SQL Injection Introduction and Prevention
SQL Injection Introduction and PreventionSQL Injection Introduction and Prevention
SQL Injection Introduction and Prevention
 
The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)The mythical technical debt. (Brooke, please, forgive me)
The mythical technical debt. (Brooke, please, forgive me)
 
What need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java DevelopersWhat need to be mastered as AI-Powered Java Developers
What need to be mastered as AI-Powered Java Developers
 
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
COMPUTER AND ITS COMPONENTS PPT.by naitik sharma Class 9th A mittal internati...
 
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdfThe Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
The Evolution of Web App Testing_ An Ultimate Guide to Future Trends.pdf
 
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
Anypoint Code Builder - Munich MuleSoft Meetup - 16th May 2024
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCAOpenChain Webinar: AboutCode and Beyond - End-to-End SCA
OpenChain Webinar: AboutCode and Beyond - End-to-End SCA
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 

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