用于在模块中定义类访问器的简写

时间:2014-03-13 13:17:48

标签: ruby metaprogramming

我发现自己编写了如下代码:

module SomeModule
  module ClassMethods
    def some_attribute
      @some_attribute
    end
    def some_attribute=(val)
      @some_attribute = val
    end
  end
  def self.included(other)
    other.extend ClassMethods
  end      
end

class MyClass
  include SomeModule
  self.some_attribute = "a value"
end

上面定义的两个类方法是否有简写?像attr_accessor这样的东西,但对于类方法。

[编辑]

根据sawa的回答,self.included方法可以更改为:

def self.included(other)
  other.singleton_class.class_eval{attr_accessor :some_attribute}
end

3 个答案:

答案 0 :(得分:3)

你可以试试这个:

module SomeModule
  def self.included(other)
    class << other 
      attr_accessor :some_attribute
    end
  end      
end

class MyClass
  include SomeModule
  self.some_attribute = "a value"
end

注意:在致电self之前不要忘记some_attribute=。你需要在writter方法上使用显式接收器,否则Ruby会认为你试图在某处指定一个变量= P

希望它有所帮助!

答案 1 :(得分:2)

class MyClass
  singleton_class.class_eval{attr_accessor :some_attribute}
end

答案 2 :(得分:1)

它也可以这样做:

module SomeModule
  attr_accessor :some_attribute
end

class MyClass
  extend SomeModule
  @some_attribute = "life is grand"
end

MyClass.some_attribute #=> "life is grand" 

但为什么不只是通常的方式呢?

class MyClass
  class << self
    attr_accessor :some_attribute
  end
end

MyClass.some_attribute = "life is grand"
MyClass.some_attribute #=> "life is grand"