ruby metaprogramming 01

Resource: Metaprogramming in Ruby


Methods look up

    receiver.method_name args

Code above demonstrated how to call a method. Receiver is optional and if you do not specified a receiver the receiver is set toself that is decide by where your method call is.

If receiver do not have method named "method_name" exists then "method_missing" will be called.  If we redefine method "method_missing" we can call anything not exist in your class.

When we call a method, ruby will go to the class of the receiver and try to find that method. It may not find it.  But remember that Ruby class inherits other classes and we can call the methods inherited from superclass. When ruby can not find what it want it will go up to the superclass and have a try.  Ruby recursively do that  following the ancestors chain. until it find that method or find the superclass is nil and then call method_missing.

Ancestors chain include not only classes but also module. When there is a module in the ancestors chain, a hidden class will be created to hold all the the methods and constants of that module.  The following example is the ancestors chain of Fixnum 1.
irb>1.class.ancestors
[Fixnum, Integer, Numeric, Comparable, Object, Kernel, BasicObject]

In the ancestors array, Kernel and Coomparable are module.


self

Your programs runs in an object called self all the time.  The object also called current object  and it is always changing. But self is a very special variable and it always references to the current object. Don't forget that : everything in ruby is object.

Some useful methods

1. send
You can call all(public/private/protected) methods out of any class.
2.send_public
       Call only public methods out of class.
3.define_method
       You can write code to define methods for your classes
4.method_missing
      This is a method called once the method you called is not exists in receiver.  And if you redefine it then you can call any methods not exists.
5.remove_method
      This method will remove a method in a class but will not remove the same method in the inheritance chain.
6.undef_method
     This one will prevents a class to respond to a method even there are same method in the ancestors.  It looks like the methods disappeared in the class and the objects created before we call undef_method will not responds to the method,

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章