Skip to content

Instantly share code, notes, and snippets.

@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
@nusco
nusco / hook_method.rb
Created August 18, 2010 14:56
Spell: Hook Method
# ==================
# Spell: Hook Method
# ==================
# Override a method to intercept object model events.
$INHERITORS = []
class C
def self.inherited(subclass)
@nusco
nusco / class_extension_mixin.rb
Created August 18, 2010 14:58
Spell: Class Extension Mixin
# ============================
# Spell: Class Extension Mixin
# ============================
# Enable a module to extend its includer through a Hook Method (http://gist.github.com/534994).
module M
def self.included(base)
base.extend(ClassMethods)
end