设置扩展类的类实例变量

时间:2013-10-03 05:20:05

标签: ruby

Foo如何返回@baz的值。目前@baz返回nil

module Bar
  @baz = 'baz'

  def get_baz
    @baz
  end
end

class Foo
  extend Bar
end

Foo.get_baz # Currently returns nil

如果这不可能,有没有更好的方法来实现这个逻辑?

1 个答案:

答案 0 :(得分:6)

试试这个:

module Bar
  attr_accessor :baz
  def get_baz
    @baz
  end
end

class Foo
  extend Bar
end

Foo.baz = 'baz'
Foo.get_baz # => 'baz'
Foo.baz # => 'baz'

如果我们看一下Foo的类方法,那当然可以:

Foo.singleton_methods # => [:get_baz, :baz, :baz=]

让我们稍微徘徊(module Bar不变):

class Foo
  extend Bar
  include Bar
end

foo = Foo.new
foo.methods.sort # => [:!,..., :baz, :baz=,..., :get_baz,...]
Foo.baz = 'baz'
foo.baz = 'cat'
Foo.baz         # => "baz" 
Foo.baz = 'dog'
foo.baz         # => "cat" 
goo = Foo.new
goo.baz = 'squid'
goo.baz         # => 'squid'

我们可以使用extendBar的特定实例引入Foo方法:

class Foo
  extend Bar
end
foo = Foo.new
foo.extend Bar
goo = Foo.new

我们使用Foofoo获得与上述相同的结果,但

goo.baz = 'rhino' # => # NoMethodError: undefined method 'baz='

无法保持extendinclude直线?也许这会有所帮助:类定义中的extend Bar等同于Foo.singleton_class.send(:include, Bar)