Metaprogramming is not a very new concept, usually metaprogramming is considered to be a program to generate the program, if from this point of view, then Lex and YACC and JAVACC should all be considered to have the concept of metaprogramming, in Java, metaprogramming has been widely used. In Ruby, however, the use of metaprogramming becomes fairly simple and easy to implement, using the Ruby language itself to generate Ruby code, without the need for external tools, the well-known ROR framework is built on the basis of Ruby Metaprogramming. You may not have any idea about metaprogramming, but Ruby has built the metaprogramming mechanism, so it's quite possible that you've already used the benefits of ruby Metaprogramming technology for you unconsciously. As in the following code:
class Person
attr_reader :name
end
You must know: name is associated with @name, but you don't necessarily know how it is implemented, in fact, the implementation of Attr_reader method is the use of metaprogramming technology, such as the following code:
class Module
def attr_reader(*syms)
syms.each do |sym|
class_eval %{def #{sym}
@#{sym}
end
end
end
end
Read this code, you should probably understand the mechanism of metaprogramming, if you do not know, then I suggest you take a serious look at Ruby's reflection mechanism, and then go on to read this post, because the content described below is not a cup of baby milk powder.
In Ruby on Rails, there is an or map layer, which is dynamically mapped from a relational table to an object, which is primarily implemented by the ActiveRecord class. In the or mapping model, when mapping a relational table in a relational database to an object model, the table name of the relational table is mapped to the class name, and each tuple in the table maps to an object corresponding to the class, and one field of the tuple corresponds to one of the attributes of the object.
If we have a file that preserves basic employee information, the format of the file is this: the first line is the name of each field of the file's contents, starting with the second line, the basic information for each employee. Now we have a file named "Employee.txt", which reads as follows:
Name,age,gender
"John", "male."
"Linclon", "male"