In ActiveRecord, you can define the association between model in a convenient declarative way, for example:
Copy Code code as follows:
Class Topic < ActiveRecord::Base
Has_many:p OSTs
Belongs_to:user
End
Has_many and belongs_to are actually class method for topic classes, and the standard notation is:
Copy Code code as follows:
Class Topic < ActiveRecord::Base
Topic.has_many (:p OSTs)
Topic.belongs_to (: User)
End
So what can has_many bring to us? The class method Has_many, when executed, adds a series of methods to the topic object instance: Posts, posts<<, Orders.push ... Wait a minute. So when we declare has_many,belongs_to in model, a series of related object methods are automatically added in. Let's try it by ourselves:
Copy Code code as follows:
Module M
def self.included (c)
C.extend (G)
End
Module G
def generate_method (*args)
Args.each do |method_name|
Define_method (method_name) {puts method_name}
End
End
End
End
Class C
Include M
GENERATE_METHOD:METHOD1,: Method2
End
c = c.new
C.method1
C.method2
We have defined a declaration Generate_method and can accept multiple symbol to dynamically create a method of the same name. Now we use this declaration in Class C: Generate_method:method1,: method2, of course we need to include module M. Why doesn't the ActiveRecord model need to include related modules? Of course, because topic's parent class ActiveRecord::Base already include the module associations.
Class C, through include module M, invokes a included callback interface of module M, letting Class C go to extend module G, in other words, to add a class method Generate_method dynamically to Class C by using the Include module M.
This generate_method is defined in Module G, which takes a series of parameters to dynamically create related methods. So we realized this DSL feature:
By declaring generate_method:method1 in Class C: METHOD2, let Class C dynamically add two instance methods Method1,method2, isn't that interesting? In fact, the Rails Object Association declaration is implemented in the same way.