Skip to content

Instantly share code, notes, and snippets.

# ====================
# Spell: Dynamic Proxy
# ====================
# Forward to another object any messages that don’t match a method.
class MyDynamicProxy
def initialize(target)
@target = target
end
@zzak
zzak / flat_scope.rb
Created September 13, 2010 16:53 — forked from nusco/flat_scope.rb
# =================
# Spell: Flat Scope
# =================
# Use a closure to share variables between two scopes.
class C
def an_attribute
@attr
end
# ===================
# 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
@zzak
zzak / hook_method.rb
Created September 13, 2010 16:53 — forked from nusco/hook_method.rb
# ==================
# Spell: Hook Method
# ==================
# Override a method to intercept object model events.
$INHERITORS = []
class C
def self.inherited(subclass)
# ====================
# Spell: Kernel Method
# ====================
# Define a method in module Kernel to make the method available to all objects.
module Kernel
def a_method
"a kernel method"
end
# =============================
# Spell: Lazy Instance Variable
# =============================
# Wait until the first access to initialize an instance variable.
class C
def attribute
@attribute = @attribute || "some value"
end
# ===================
# Spell: Mimic Method
# ===================
# Disguise a method as another language construct.
def BaseClass(name)
name == "string" ? String : Object
end
@zzak
zzak / monkeypatch.rb
Created September 13, 2010 16:53 — forked from nusco/monkeypatch.rb
# ==================
# Spell: Monkeypatch
# ==================
# Change the features of an existing class.
"abc".reverse # => "cba"
class String
def reverse
# ======================
# Spell: Named Arguments
# ======================
# Collect method arguments into a hash to identify them by name.
def my_method(args)
args[:arg2]
end
@zzak
zzak / namespace.rb
Created September 13, 2010 16:53 — forked from nusco/namespace.rb
# ================
# Spell: Namespace
# ================
# Define constants within a module to avoid name clashes.
module MyNamespace
class Array
def to_s
"my class"