Ruby のカプセル化は難しい

id:no6v さんに指摘されて気が付いた。

Cook::Pan クラスはカプセル化できていない。

asin:4894714515 にも、こう書いてあったのに。

オブジェクト内部のデータへの「ハンドル」を戻さないようにしよう

そんなつもりなく、やっちまった。

修正版。

# 名前空間のための module
module Cook
  # なべを用意
  class Pan
    # なべには食べごろの時間と中の食材がある
    def initialize(good_for_eating)
      @good_for_eating = good_for_eating
      @ingredient = []
    end

    # なべに食材を投入
    def <<(o)
      @ingredient << o
      self              # ←コレを追加
    end

    # なべを火にかける
    def boil
      @st = Time.now
      self              # ←コレを追加
    end

    # 調理の経過時間 (秒)
    def elapsed_time
      if @st.nil?
        0
      else
        Time.now - @st
      end
    end

    # 食べごろ?
    def eatable?
      if @st.nil?
        false
      else
        @good_for_eating.include?(Time.now - @st)
      end
    end
  end
end

self を返すために delegate も止めた。

Cook::Pan#boil の方は Time に破壊的メソッドがないから平気だったのね。

pp curry << :apple << :honey
# >> #<Cook::Pan:0x10013e10
# >>  @good_for_eating=4500..4620,
# >>  @ingredient=[:onion, :beef, :carrot, :potato, :apple, :honey],
# >>  @st=2009-07-28 22:22:27 +0900>