派生类没有基类属性的值

时间:2013-02-04 07:54:02

标签: ruby

module Module1
  class Base1
    class << self
      attr_accessor :attr1, :attr2
      def configure
        yield(self) if block_given?
      end
    end
  end
end 

module Module1
  class Child1 < Base1
     def self.some_method1
       #... some stuff
       "#{attr1}_123"  #for some reason attr1 is nil
     end
  end
end 


  Module1::Base1.configure do |item|
    item.method1 = "43243243"
    item.method2 = "fdsfdsfd"
  end




  data1 = Module1::Child1.some_method1 #it doesn't return what I expect

由于某些原因,attr1Child1#some_method1 nilModule1::Base1.method1不同,{{1}}中有值{{1}}。我想知道为什么以及我该怎么做才能摆脱它?

2 个答案:

答案 0 :(得分:1)

attr_accessor创建实例变量,因此您的代码正在创建类实例变量:因为类是对象,所以它们也可以包含实例变量。这些变量不是继承的。

还有类变量(@@foo),这可能会令人惊讶 - 如果更改派生类中的值,它会为整个层次结构更改它。

Ruby没有一种变量,它以与方法继承相同的方式继承。诸如活动支持之类的库添加attr_accessor版本(活动支持称为class_attribute),它设置了正确的钩子以创建行为类似的访问器 - 您可以查看该源的源代码< / p>

答案 1 :(得分:1)

首先,我想应该有s/method/attr/g

Module1::Base1.configure do |item|
  item.method1 = "43243243"
  item.method2 = "fdsfdsfd"
end

中学,在some_method1我们称之为eigenclass'attr:

#... some stuff
"#{Base1.attr1}_123"  #for some reason attr1 is nil

得到以下特性:

#!/usr/bin/ruby

module Module1
  class Base1
    class << self
      attr_accessor :attr1, :attr2
      def configure
        yield(self) if block_given?
      end
    end
  end
end 

module Module1
  class Child1 < Base1
     def self.some_method1
       #... some stuff
       "#{Base1.attr1}_123"  #for some reason attr1 is nil
     end
  end
end

Module1::Base1.configure do |item|
  item.attr1 = "43243243"
  item.attr2 = "fdsfdsfd"
end

puts Module1::Child1.some_method1 #it does return what I expect

给出:

$ /tmp/a.rb
43243243_123