Fastest/One-liner way to list attr_accessors in Ruby?

前端 未结 6 833
忘了有多久
忘了有多久 2020-12-02 14:16

What\'s the shortest, one-liner way to list all methods defined with attr_accessor? I would like to make it so, if I have a class MyBaseClass, any

6条回答
  •  借酒劲吻你
    2020-12-02 15:10

    Extract the attributes in to an array, assign them to a constant, then splat them in to attr_accessor.

    class SubClass < MyBaseClass
      ATTRS = [:id, :title, :body]
      attr_accessor(*ATTRS)
    end
    

    Now you can access them via the constant:

    puts SubClass.ATTRS #=> [:id, :title, :body]
    

提交回复
热议问题