ActiveSupport 中 mattr_accessor 和 cattr_accessor 的区别? [英] Difference between mattr_accessor and cattr_accessor in ActiveSupport?

查看:41
本文介绍了ActiveSupport 中 mattr_accessor 和 cattr_accessor 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过查看源代码,我无法弄清楚 Class 和 Module 中分别提供的 cattr_*mattr_* 方法之间的区别.我读过这个问题:Rails 模块中的 mattr_accessor 是什么? 提供了两种方法的一些细节,但没有突出差异.

I can't work out from looking through the source what the difference is between the cattr_* and mattr_* methods provided in Class and Module respectively. I read this question: What is mattr_accessor in a Rails module? which gives some details about both methods but doesn't highlight the differences.

所以我的问题是它们之间有什么区别,为什么我们需要两组方法,因为它们在源代码中几乎相同?另外,我们应该在什么时候使用哪个?

So my question is what is the difference between them and why do we need both sets of methods when they are practically identical in the source? Also, which should we use when?

推荐答案

ModuleClass 类的超类,所以如果可以想到一个合适的通用名称定义访问器的方法可以放在 Module 上,它适用于模块和类.请注意以下工作:

Module is the superclass of the class Class so if a suitably generic name could be thought of then the methods for defining accessors could be put on Module and it would work for modules and classes. Notice that the follow works:

class Bar
  mattr_accessor :test
end

但是

module Foo
  cattr_accessor :test
end

行不通.

在应该在类内部使用的方法上有一个 c 前缀,在模块内部使用的方法上有一个 m 前缀只是有助于让你的代码更清晰一些.

Having a c prefix on the methods that should be used inside classes and an m prefix on the methods for use inside modules just helps to make your code a bit clearer.

这篇关于ActiveSupport 中 mattr_accessor 和 cattr_accessor 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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