コールバック
昨日Rails勉強会に久しぶりに参加した.Observerパターン.
コールバックしたい時に、きっちり型を出さないならブロックだろうなぁと思った。
その場で試したくなったがノートを持たない私. ノートがほしくなった.
class Counter def initialize @count = 0 @listeners = [] end def up @count += 1 fire end def add_listener &block @listeners << block end def fire @listeners.each { |listener| listener.call @count } end end counter = Counter.new counter.add_listener { |count| puts "hoge: count=#{count}" } counter.add_listener { |count| puts "fuga: count=#{count}" } counter.up counter.up
あと、Railsをトレースしなきゃねw.