Skip to content

Instantly share code, notes, and snippets.

@nusco
nusco / class_instance_variable.rb
Created August 18, 2010 15:00
Spell: Class Instance Variable
# ==============================
# 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
@nusco
nusco / class_macro.rb
Created August 18, 2010 15:01
Spell: Class Macro
# ==================
# Spell: Class Macro
# ==================
# Use a class method in a class definition.
class C; end
class << C
def my_macro(arg)
@nusco
nusco / clean_room.rb
Created August 18, 2010 15:02
Spell: Clean Room
# =================
# 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
@nusco
nusco / string_of_code.rb
Created August 18, 2010 15:06
Spell: String of Code
# =====================
# Spell: String of Code
# =====================
# Evaluate a string of Ruby code.
my_string_of_code = "1 + 1"
eval(my_string_of_code) # => 2
# For more information: http://www.pragprog.com/titles/ppmetr/metaprogramming-ruby
@nusco
nusco / code_processor.rb
Created August 18, 2010 15:07
Spell: Code Processor
# =====================
# 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
@nusco
nusco / context_probe.rb
Created August 18, 2010 15:08
Spell: Context Probe
# ====================
# Spell: Context Probe
# ====================
# Execute a block to access information in an object’s context.
class C
def initialize
@x = "a private instance variable"
end
@nusco
nusco / deferred_evaluation.rb
Created August 18, 2010 15:10
Spell: Deferred Evaluation
# ==========================
# 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
@nusco
nusco / dynamic_dispatch.rb
Created August 18, 2010 15:12
Spell: Dynamic Dispatch
# =======================
# Spell: Dynamic Dispatch
# =======================
# Decide which method to call at runtime.
method_to_call = :reverse
obj = "abc"
obj.send(method_to_call) # => "cba"
@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
@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