开发者

Error when adding an observer in Ruby

开发者 https://www.devze.com 2023-03-24 14:04 出处:网络
I am using Ruby 1.9.2, and I have a class that uses the observer mixin: require \'observer\' class Street

I am using Ruby 1.9.2, and I have a class that uses the observer mixin:

require 'observer'

class Street
  include Observable

  attr_accessor :current

  def initialize current
    @current = current
  end

  def reset
    @current = :preflop
  end

  def receive street
    @current = street
    changed  
    notify_observers
  end

end

But when I try to add an observer like:

  def initialize  
    @street = Street.new(:preflop)
    @stats = Stats.new 
    @street.add_observer(@stats)
  end

I get this error:

 can't convert nil into Integer (TypeError)

Which occurs on the last line of add_observer:

  def add_observer(observer, func=:update)
    @observer_peers = {} unless defined? @observer_peers
    unless observer.respond_to? func
      raise NoMethodError, "observer does not respond to `#{fu开发者_如何学Pythonnc.to_s}'"
    end
    @observer_peers[observer] = func
  end

EDIT: this turned out to be an issue with my having a attr_accessor on a variable called (erm) @hash. Apparently there was some conflict with the observable mixin.


Pasted code in irb under ruby 1.9.2-p180 and typed

Something.new

Seemed to work. Got back:

<Something:0x00000100ac9238 @street=#<Street:0x00000100ac9210 @current=:preflop, @observer_peers={#<Stats:0x00000100ac91e8 @stats="hey">=>:update}>, @stats=#<Stats:0x00000100ac91e8 @stats="hey">>

Not claiming that this has anything to do with reality or sinatra. Just running some code in irb to see if it gets the same error, which it did not. Barked about not responding to update so I put that in.

Here is the code:

require 'observer'

class Street
  include Observable

  attr_accessor :current

  def initialize current
    @current = current
  end

  def reset
    @current = :preflop
  end

  def receive street
    @current = street
    changed
    notify_observers
  end
end

class Stats
  def initialize
    @stats = 'hey'
  end

  def update
    @stats = 'ho'
  end
end

class Something
  def initialize
    @street = Street.new( :preflop )
    @stats = Stats.new
    @street.add_observer( @stats )
  end
end


this turned out to be an issue with my having a attr_accessor on a variable called (erm) @hash. Apparently there was some conflict with the observable mixin.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号