KEMBAR78
Ruby Metaprogramming | PPT
Ruby Metaprogramming
About me Lu Wei Jen http://blog.weijen.net http://www.facebook.com/weijenlu Twitter: weijenlu
Metaprogramming Metaprogramming is writing code that manipulates language constructs at runtime.
Agenda Object, Class and Module Singleton Methods and Metaclass Block Eval family
Part 1. Object, Class and Module Object introspection Classes  Module Singleton Method Method Lookup Dynamic Methods Hook methods
Object Introspection
Metaprogramming Ruby p.38 Objects of the same class share methods, but they don’t share instance variables.
Classes Classes themselves are nothing but  objects . Classes are instances of a class called  Class .
Method Lookup One step to the right, then up. obj @val MyClass my_method() class() Object
Open Class You can always reopen existing classes, and modify them.
Module Modules are also objects. When you include a module: Ruby creates an anonymous class wraps the module. Ruby then insert anonymous class into the ancestors chain.
Module obj @val Myclass my_method (M) m_method Object class
Singleton Method
Class Method are Singleton Method
Metaclass Where is singleton method? An object can have its own special, hidden class named Metaclass. Also named eigenclass. obj @val Myclass my_method (M) m_method Object class
Metaclass
Define Class Methods
What about module?
Method Lookup Review obj @val MyClass my_method (M) m_method Object class #obj my_singleton_method #MyClass class_method_1 class_method_2 #(M) m_class_method #Object
Define Methods Dynamically
Calling Method Dynamically
method_missing() If method can’t be find, then  self  calling method_missing(). It’s an instance method of  Kernel  that every object inherits. It responded by raising a  NoMethodError .
Overriding method_missing()
 
Hook methods inherited() included()
Part 2. Block Block Scope Callable Objects
Block
Scope (But don’t do that)
Scope Gates Class definitions Module definitions methods
Proc Object
The & Operator A block can be an argument to a method. Block argument: must be  the last  in the list of arguments. Must  prefixed  by an  &  sign. &  operator convert the  block to a Proc object. &  operator also can convert the  Proc object to block.
The & Operator
Part 3. Eval* family eval instance_eval module_eval(class_eval)
Kernel#eval() it takes a string of code. It executes the code in the string.
The troble with eval() Your editor’s features mayn’t support. Not easy to read and modify. Not easy to debug. Code Injection
Object#instance_eval
Module#class_eval(module_eval)
Classes themselves are nothing but  objects .
Thanks
Q&A

Ruby Metaprogramming