Ruby 编程:类实例变量与模块的高效运用
1. 类实例变量与类变量的运用
1.1 类实例变量示例
类实例变量在 Ruby 代码中较为常见。以下是一个 Document 类,它包含类实例变量 @default_font ,并提供了获取和设置默认字体的类方法:
class Document
@default_font = :times
class << self
attr_accessor :default_font
end
# Rest of the class omitted...
end
运行上述代码后, Document 类就具备了获取和设置默认字体的功能。
1.2 类实例变量在 ActiveRecord 中的应用
在 Rails 开发中,ActiveRecord 对象的回调方法是类实例变量的典型应用。例如,在 Person 类中,我们可以设置在记录保存到数据库后调用 handle_after_save 方法:
class Person < ActiveRecord::Base
after_save :handle_after_save
def handle_after_save
# Do something after the record is s
超级会员免费看
订阅专栏 解锁全文
379

被折叠的 条评论
为什么被折叠?



