Ruby - 实例方法中未初始化的类变量

时间:2017-05-23 20:39:28

标签: ruby mixins instance-variables class-variables

我正在研究RoR课程并且在irb控制台中收到错误: " NameError:InstanceCounter中的未初始化的类变量@@实例:: InstanceMethods"

我需要在modules.rb中更改什么?

控制台:

Evgenys-MacBook-Pro-2:lesson_05 admin$ irb
2.3.1 :001 > load 'modules.rb'
 => true 
2.3.1 :002 > load 'car.rb'
 => true 
2.3.1 :003 > car=Car.new
initialize
NameError: uninitialized class variable @@instances in InstanceCounter::InstanceMethods
Did you mean?  instance_methods
from modules.rb:35:in `initialize'
from (irb):3:in `new'
from (irb):3
from /Users/aku/.rvm/rubies/ruby-2.3.1/bin/irb:11:in `<main>'

modules.rb:

module InstanceCounter
  module ClassMethods

    @@instances = 0

    def instances
      puts "@@instances"
      @@instances
    end

  end

  module InstanceMethods

    def initialize
      puts "initialize"
      register_instance
      super
    end

    protected

    def register_instance
      @@instances += 1
      puts "@@instances += 1"
    end

  end

  def self.included(base)
    base.extend ClassMethods
    base.send :prepend, InstanceMethods
  end
end

car.rb:

class Car
  include InstanceCounter

  def initialize
    puts "initialize2"
  end  
end

class PassengerCar < Car
end

class CargoCar < Car
end

1 个答案:

答案 0 :(得分:0)

将类变量放在InstanceMethods模块中。看起来extend默认情况下只向调用对象添加方法。

有关默认ruby实现的文档以供参考:extendinclude