Skip to content

Instantly share code, notes, and snippets.

@nusco
nusco / open_class.rb
Created August 18, 2010 15:27
Spell: Open Class
# =================
# Spell: Open Class
# =================
# Modify an existing class.
class String
def my_string_method
"my method"
end
@nusco
nusco / nil_guard.rb
Created August 18, 2010 15:26
Spell: Nil Guard
# ================
# Spell: Nil Guard
# ================
# Override a reference to nil with an “or.”
x = nil
y=x || "avalue" # =>"avalue"
# For more information: http://www.pragprog.com/titles/ppmetr/metaprogramming-ruby
@nusco
nusco / namespace.rb
Created August 18, 2010 15:25
Spell: Namespace
# ================
# Spell: Namespace
# ================
# Define constants within a module to avoid name clashes.
module MyNamespace
class Array
def to_s
"my class"
@nusco
nusco / named_arguments.rb
Created August 18, 2010 15:23
Spell: Named Arguments
# ======================
# Spell: Named Arguments
# ======================
# Collect method arguments into a hash to identify them by name.
def my_method(args)
args[:arg2]
end
@nusco
nusco / mimic_method.rb
Created August 18, 2010 15:22
Spell: Mimic Method
# ===================
# Spell: Mimic Method
# ===================
# Disguise a method as another language construct.
def BaseClass(name)
name == "string" ? String : Object
end
@nusco
nusco / lazy_instance_variable.rb
Created August 18, 2010 15:21
Spell: Lazy Instance Variable
# =============================
# Spell: Lazy Instance Variable
# =============================
# Wait until the first access to initialize an instance variable.
class C
def attribute
@attribute = @attribute || "some value"
end
@nusco
nusco / kernel_method.rb
Created August 18, 2010 15:16
Spell: Kernel Method
# ====================
# 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
@nusco
nusco / flat_scope.rb
Created August 18, 2010 15:15
Spell: Flat Scope
# =================
# Spell: Flat Scope
# =================
# Use a closure to share variables between two scopes.
class C
def an_attribute
@attr
end
@nusco
nusco / dynamic_proxy.rb
Created August 18, 2010 15:14
Spell: Dynamic Proxy
# ====================
# Spell: Dynamic Proxy
# ====================
# Forward to another object any messages that don’t match a method.
class MyDynamicProxy
def initialize(target)
@target = target
end
@nusco
nusco / dynamic_method.rb
Created August 18, 2010 15:13
Spell: Dynamic Method
# =====================
# Spell: Dynamic Method
# =====================
# Decide how to define a method at runtime.
class C
end
C.class_eval do