Книга: Metaprogramming Ruby 2
Назад: Chapter 12: The Evolution of Attribute Methods
Дальше: A History of Complexity

Attribute Methods in Action

Assume that you’ve created a database table that contains tasks.

​ 
require ​'active_record'​
​ 
ActiveRecord::Base.establish_connection :adapter => ​"sqlite3"​,
​ 
:database => ​"dbfile"​
​ 
​ 
ActiveRecord::Base.connection.create_table :tasks ​do​ |t|
​ 
t.string :description
​ 
t.boolean :completed
​ 
​end​

Now you can define an empty Task class that inherits from ActiveRecord::Base, and you can use objects of that class to interact with the database:

​ 
​class​ Task < ActiveRecord::Base; ​end​
​ 
​ 
task = Task.new
​ 
task.description = ​'Clean up garage'​
​ 
task.completed = true
​ 
task.save
​ 
​ 
task.description ​# => "Clean up garage"​
​ 
task.completed? ​# => true​

The previous code calls four accessor methods to read and write the object’s attributes: two write accessors (description= and completed=), one read accessor (description), and one query accessor (completed?). None of these Mimic Methods () comes from the definition of Task. Instead, Active Record generated them by looking at the columns of the tasks table. These automatically generated accessors are called attribute methods.

You probably expect that attribute methods such as description= are either Ghost Methods () implemented through method_missing or Dynamic Methods () defined with define_method. Things are actually more complicated than that, as you’ll find out soon.

Назад: Chapter 12: The Evolution of Attribute Methods
Дальше: A History of Complexity