Observer notify_observers()如何将* args传递给observer

时间:2014-07-15 09:10:13

标签: ruby observer-pattern observable

以下是代码:

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。 我对上层理解是对的吗?

我对上层代码有两个问题:

  1. 班级Notifier只有一个方法update,没有initialize。那么*argsself, miles)会直接传递给update吗?

  2. self中的self, miles是静态的还是动态的?是car还是其他什么?

1 个答案:

答案 0 :(得分:0)

  1. 是。 Here's what it does

    #File activemodel/lib/active_model/observing.rb, line 73
    def notify_observers(*arg)
      observer_instances.each { |observer| observer.update(*arg) }
    end
    
  2. self将在调用notify_observers时成为值。因此,在这种情况下,它将是您Carlog的{​​{1}}实例。