【问题标题】:explicit `attr_writer` for Rails models in order to add YARD docRails 模型的显式 `attr_writer` 以添加 YARD 文档
【发布时间】:2017-02-19 07:14:43
【问题描述】:

假设我创建了一个 Rails 模型:

rails generate model SuperModel name:string

然后它为新表创建迁移:

create_table 'super_models' |t|
    t.string  'name'
    ...
end

还有一个模型类:

class SuperModel < ActiveRecord::Base ...

我知道 rails 会为 name 属性生成一些方法,类似于我可以手动执行的操作:

class SuperModel < ActiveRecord::Base
    # YARD doc
    # @attr [String] ...
    attr_writer :name
end

然后可以通过 doc-tools 和自动完成获取项目文档,并使用 IntelliJ(+RubyMine 等)进行就地文档查找

这可能是 XY 问题,但如果我手动添加 attr_writer 属性,这将如何影响 ActiveRecord 等生成的方法(如 super_model.changed?)的工作方式。我想要的是编译语言功能,例如 IDE 中的类型检查/自动完成和文档。

【问题讨论】:

  • 您可以添加 Yard @attr 标签,而无需显式添加 getter/setter。自从我使用 Rubymine 已经有一段时间了,但我相信它实际上会读取架构并获取属性。

标签: ruby-on-rails intellij-idea model attributes rubymine


【解决方案1】:

attr_readerattr_writerattr_accessor 是添加 setter 和 getter 的元编程实用方法。因此在模型上使用它们可能会破坏 ActiveModel 设置器,这可能会弄乱诸如污点检查和ActiveModel::Dirty 之类的事情。

【讨论】:

    猜你喜欢
    • 2011-11-08
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多