Rails 模块中的 mattr_accessor 是什么? [英] What is mattr_accessor in a Rails module?
问题描述
我在 Rails 文档中真的找不到这个,但似乎 'mattr_accessor' 是 'attr_accessor' 的 Module 推论(getter & setter)在一个普通的Ruby 类中.
I couldn't really find this in Rails documentation but it seems like 'mattr_accessor' is the Module corollary for 'attr_accessor' (getter & setter) in a normal Ruby class.
例如.在一个班级
class User
attr_accessor :name
def set_fullname
@name = "#{self.first_name} #{self.last_name}"
end
end
例如.在一个模块中
module Authentication
mattr_accessor :current_user
def login
@current_user = session[:user_id] || nil
end
end
此辅助方法由 ActiveSupport 提供.
This helper method is provided by ActiveSupport.
推荐答案
Rails 通过 mattr_accessor
(模块访问器)和 cattr_accessor
(以及 _reader
/_writer
版本).由于Ruby的attr_accessor
为实例生成getter/setter方法,cattr/mattr_accessor
在类提供getter/setter方法或模块级.因此:
Rails extends Ruby with both mattr_accessor
(Module accessor) and cattr_accessor
(as well as _reader
/_writer
versions). As Ruby's attr_accessor
generates getter/setter methods for instances, cattr/mattr_accessor
provide getter/setter methods at the class or module level. Thus:
module Config
mattr_accessor :hostname
mattr_accessor :admin_email
end
是:
module Config
def self.hostname
@hostname
end
def self.hostname=(hostname)
@hostname = hostname
end
def self.admin_email
@admin_email
end
def self.admin_email=(admin_email)
@admin_email = admin_email
end
end
两个版本都允许您像这样访问模块级变量:
Both versions allow you to access the module-level variables like so:
>> Config.hostname = "example.com"
>> Config.admin_email = "admin@example.com"
>> Config.hostname # => "example.com"
>> Config.admin_email # => "admin@example.com"
这篇关于Rails 模块中的 mattr_accessor 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!