主要介绍了Ruby Metaprogramming的机制和方法。主要包括:
Introspection
Dynamic dispatch/Dynamic method
Ghost Method
Ruby Alias and AOP
Object/Class Extension
Eval/Class Eval/Instance Eval/Module Eval
Ruby Object Model
Singleton class/Metaclass/Eigenclasses
Hook Method
Module and Class Mixin Extension
Block、Callable Object and Functional programming
Domain Specific Language
另附带两段代码没往
ppt写:
Open class and sexy api:
#!/usr/bin/ruby
class Numeric
def weeks
return 7 * self.days
end
def days
return 24 * self.hours
end
def hours
return 60 * self.minutes
end
def minutes
return 60 * self.seconds
end
def seconds
return self
end
def ago
return Time.now - self
end
def after
return Time.new + self
end
end
p 3.minutes.ago
p 3.days.ago
p 3.days.after
class macro:
class Object
def self.my_attr_accessor(sym)
class_eval <<EOF
def #{sym}
instance_variable_get(:@#{sym})
end
def #{sym}=(value)
instance_variable_set(:@#{sym},value)
end
EOF
end
end
class A
my_attr_accessor :a
def initialize(a)
@a = a
end
end
a_ins = A.new(1)
a_ins.a = 22
puts a_ins.a
附件有ppt