You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby模块是否有类似attr_accessor、attr_reader的便捷属性定义方法?

模块类级属性的简化实现

在纯Ruby环境下,你可以通过**模块的单例类(eigenclass)**来使用attr_accessor,实现和类级属性一样的便捷读写:

module MyMod
  # 切换到模块的单例类上下文,定义属性访问器
  class << self
    attr_accessor :property
  end

  # 初始化属性值
  self.property = 'whatever'
end

puts MyMod.property # => whatever
MyMod.property = 'dude'
puts MyMod.property # => dude

原理说明

class << self块会切换到模块自身的单例类上下文,此时调用的attr_accessor会直接为模块生成property(读方法)和property=(写方法)这两个类级方法,和你手动编写的逻辑完全一致,但代码更简洁。

如果是在Rails环境中,框架提供了更便捷的mattr_accessor方法(module attribute accessor),无需手动操作单例类:

module MyMod
  mattr_accessor :property
  self.property = 'whatever'
end

这个方法会自动为模块生成类级的读写属性,用法和类的attr_accessor完全一致,是Rails开发中的常用写法。

内容的提问来源于stack exchange,提问作者tscheingeld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 12:52:07