How To PUNCH A DUCK
Will Engler
What I Will Say
- How is Rails magical?
- What is duck typing?
- What is duck punching?
Rails is Magical
But how?
TIME
> rails console
> 2.days.ago
=> Sat, 28 Feb 2015 22:31:59 UTC +00:00
1.month.from_now
=> Thu, 02 Apr 2015 22:32:24 UTC +00:00
Routes
Rails.application.routes.draw do
resources :cats
root 'cats#index'
Is Rails a dsl?
- Matz thinks so
- (DSL: Domain Specific Language)
Duck Typing
Static Typing
public int add(int a, int b){
return a + b
}
public String add(String a, String b){
return a + b
}
Dynamic Typing
def add(a, b)
a + b
end
Duck typing
If it walks like a duck...
duck typing is a style of typing in which an object's methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of an explicit interface
-Wikipedia
Duck Type Checking
#Ruby
> 2.respond_to?(:+)
=> true
#Python
def is_leaf(node):
try:
if tree.label:
return True
except AttributeError:
return False
Duck Punching Time
What is Duck Punching?
- A way to modify a class at run time
- Even if you didn't create it
- "Reopen" a class and change it
- AKA monkey patching
Danger!
- Can lead to obtuse code
- But in the hands of a pro, cool things can happen
- Rails Active Support
Takeaways
- The "freedom" of dynamic languages
- Rails is built on Ruby for a reason
- OOP is a wide umbrella
How To Punch A Duck
By Will Engler
How To Punch A Duck
Pitt CSC 3/2/15
- 768