Skip to content

Instantly share code, notes, and snippets.

@nusco
nusco / inheritance_sucks_1.rb
Created August 18, 2010 12:07
Post: "Why Inheritance Sucks"
class Bird
def fly
"Wheee!"
end
end
class Duck < Bird
end
donald = Duck.new
@nusco
nusco / inheritance_sucks_2.rb
Created August 18, 2010 12:09
Post: "Why Inheritance Sucks"
module Bird
def fly
"Wheee!"
end
end
class Duck
include Bird
end
@nusco
nusco / object_extension.rb
Last active September 5, 2015 18:54
Spell: Object Extension
# =======================
# Spell: Object Extension
# =======================
# Define Singleton Methods by mixing a module into an object’s singleton class.
obj = Object.new
module M
def my_method
@nusco
nusco / class_extension.rb
Last active September 15, 2015 06:19
Spell: Class Extension
# ======================
# Spell: Class Extension
# ======================
# Define class methods by mixing a module into a class’s singleton class
# (a special case of Object Extension - http://gist.github.com/534667).
class C; end
module M
@nusco
nusco / singleton_method.rb
Created August 18, 2010 13:14
Spell: Singleton Method
# =======================
# Spell: Singleton Method
# =======================
# Define a method on a single object.
obj = "abc"
class << obj
def my_singleton_method
@nusco
nusco / monkeypatch.rb
Created August 18, 2010 13:15
Spell: Monkeypatch
# ==================
# Spell: Monkeypatch
# ==================
# Change the features of an existing class.
"abc".reverse # => "cba"
class String
def reverse
@nusco
nusco / argument_array.rb
Created August 18, 2010 13:42
Spell: Argument Array
# =====================
# Spell: Argument Array
# =====================
# Collapse a list of arguments into an array.
def my_method(*args)
args.map {|arg| arg.reverse }
end
@nusco
nusco / around_alias.rb
Created August 18, 2010 13:45
Spell: Around Alias
# ===================
# Spell: Around Alias
# ===================
# Call the previous, aliased version of a method from a redefined method.
class String
alias :old_reverse :reverse
def reverse
@nusco
nusco / ghost_method.rb
Created August 18, 2010 13:47
Spell: Ghost Method
# ===================
# Spell: Ghost Method
# ===================
# Respond to a message that doesn’t have an associated method.
class C
def method_missing(name, *args)
name.to_s.reverse
end
@nusco
nusco / blank_slate.rb
Last active September 5, 2015 18:54
Spell: Blank Slate
# ===================
# Spell: Blank Slate
# ===================
# Remove methods from an object to turn them into Ghost Methods (http://gist.github.com/534776).
class C
def method_missing(name, *args)
"a Ghost Method"
end