Skip to content

Instantly share code, notes, and snippets.

# ======================
# Spell: Class Extension
# ======================
# Define class methods by mixing a module into a class’s eigenclass
# (a special case of Object Extension - http://gist.github.com/534667).
class C; end
module M
# ============================
# 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
# ==============================
# Spell: Class Instance Variable
# ==============================
# Store class-level state in an instance variable of the Class object.
class C
@my_class_instance_variable = "some value"
def self.class_attribute
@zzak
zzak / class_macro.rb
Created September 13, 2010 16:54 — forked from nusco/class_macro.rb
# ==================
# Spell: Class Macro
# ==================
# Use a class method in a class definition.
class C; end
class << C
def my_macro(arg)
@zzak
zzak / clean_room.rb
Created September 13, 2010 16:54 — forked from nusco/clean_room.rb
# =================
# Spell: Clean Room
# =================
# Use an object as an environment in which to evaluate a block.
class CleanRoom
def a_useful_method(x); x * 2; end
end
# =====================
# Spell: Code Processor
# =====================
# Process Strings of Code (http://gist.github.com/535047) from an external source.
File.readlines("file_containing_lines_of_ruby.txt").each do |line|
puts "#{line.chomp} ==> #{eval(line)}"
end
# ====================
# Spell: Context Probe
# ====================
# Execute a block to access information in an object’s context.
class C
def initialize
@x = "a private instance variable"
end
# ==========================
# Spell: Deferred Evaluation
# ==========================
# Store a piece of code and its context in a proc or lambda for evaluation later.
class C
def store(&block)
@my_code_capsule = block
end
# =======================
# Spell: Dynamic Dispatch
# =======================
# Decide which method to call at runtime.
method_to_call = :reverse
obj = "abc"
obj.send(method_to_call) # => "cba"
# =====================
# Spell: Dynamic Method
# =====================
# Decide how to define a method at runtime.
class C
end
C.class_eval do