什么是mattr_accessor在Rails模块? [英] What is mattr_accessor in a Rails module?

查看:176
本文介绍了什么是mattr_accessor在Rails模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails文档中找不到,但'mattr_accessor''attr_accessor'模块 getter& setter)。

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


b $ b

例如。在模块中

Eg. in a module

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 (以及_ 阅读器 / _writer 版本)。因为Ruby的 attr_accessor 实例生成getter / setter方法 cattr / mattr_accessor set方法在模块级别。因此:

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"

这篇关于什么是mattr_accessor在Rails模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆