以下是代码:
class Notifier
def update(car, miles)
puts "The car has logged #{miles} miles, totaling #{car.mileage} miles traveled."
puts "The car needs to be taken in for a service!" if car.service <= car.mileage
end
end
require 'observer'
class Car
include Observable
attr_reader :mileage, :service
def initialize(mileage = 0, service = 3000)
@mileage, @service = mileage, service
add_observer(Notifier.new)
end
def log(miles)
@mileage += miles
changed
notify_observers(self, miles)
end
end
car = Car.new(2800, 3000)
car.log(100)
car.log(100)
此处,方法notify_observers(self, miles)
会将*args
(此处为self, miles
)传递给观察者(Notifier.new
的实例) add_observer
。
我对上层理解是对的吗?
我对上层代码有两个问题:
班级Notifier
只有一个方法update
,没有initialize
。那么*args
(self, miles
)会直接传递给update
吗?
self
中的self, miles
是静态的还是动态的?是car
还是其他什么?
答案 0 :(得分:0)
#File activemodel/lib/active_model/observing.rb, line 73
def notify_observers(*arg)
observer_instances.each { |observer| observer.update(*arg) }
end
self
将在调用notify_observers
时成为值。因此,在这种情况下,它将是您Car
上log
的{{1}}实例。