Metaprogramming Ruby - Class Definitions Note

how Ruby def class

  1. The Ruby interpreter always keeps a reference to the current class (or module). All methods defined with def become instance methods of the current class.
  2. current object self and the current class are the same
  3. you can use class_eval to open a class.

concepts or methods

current class: the self of class
class_eval: open a class, just mean you can add new staff to the class
class instance variable: instance variable to a class, can't access by subclasses or a instance methods
class variables: can access by subclasses, can access by instance methods. But class variables in main will cause problem. Because main belongs to main’s class Object...and to all the descendants of Object. :(

stub without stub

 # add an abstraction level
 def self.time_class
   @time_class || Time
 end

 # useage
 Loan.instance_eval { @time_class = FakeTime }

def class without class keyword

Js can define Function without Function def syntax too.

 c = Class.new(Array) do
   def my_method
     'Hello!'
   end
 end

Introducing Singleton Methods

duck typing: Just make OO more like function programing.
For function programing, we don't care what is it, we just care, what it can do.
So functional programing dosen't care about it is a duck or not, just if it can quack.

Singleton

An object can has its own special, hidden class. That’s called the singleton class of the object

Singleton method lives in singleton class.

 Object#singleton_class
 singleton_class = class << obj
   self
 end

singleton_class.instance_methods.grep(/my_/)

why?

Ruby designer think we can add method to an obj.
So they add a special class to obj, and call it singleton class.
So we can add method to an object and the method lives in its singleton class.

As we know, a class is object too, that means we can add singleton class,and we can have singleton methods to it too.
Then we call an Class' singleton method "class method".

how to access singleton method in inheritance?

There is a class called A, and it inherit from B, I mean B is superclass of A.

Then A's singlton class' supperclass is B's singlton class.

Let me try to say these a again.
A class' singleton class superclass is its superclass' singleton class.

Cheer!

The Thor Example, hook or before after

Use alias_method, Rails do before by this way.

ruby's alias_method is deep copy.

Python use decorator do similar thing.

More Method Wrappers

  1. refine
  2. prepend

你可能感兴趣的:(Metaprogramming Ruby - Class Definitions Note)