2012年8月26日日曜日

delegateメソッドの使い方について

class Zombie < ActiveRecord::Base
  attr_accessible :name, :status
  has_many :tweets

  def hello
    "hi zombie"
  end

  def goodbye
    "bye zombie"
  end
  
  def goodnight
    "goodnight"
  end
end

class Tweet < ActiveRecord::Base
  attr_accessible :content, :zombie_id
  belongs_to :zombie
  delegate :hello, :to => :zombie
  delegate :hello, :to => :zombie, :prefix => true
  delegate :hello, :to => :zombie, :prefix => "great"
  delegate :hello, :to => :zombie

  delegate :goodbye, :to => :zombie
  delegate :goodnight, :to => :zombie, :allow_nil => true
end

t = Tweet.first
t.hello
t.zombie_hello
t.great_hello

t = Tweet.last #t.zombie nil
t.goodbye 
t.goodnight
実行結果
  • 通常。"hi zombie"
  •  prefixをtrueにすると:toの名前が前につく。"hi zombie"
  •  prefixを自分で指定。"hi zombie" 
  • TweetがZombieを持っていない時にdelegateを実行。RuntimeError: Tweet#goodbye delegated to zombie.goodbye, but zombie is nil 
  • TweetがZombieを持っていない時にdelegateを実行。
    nil

0 件のコメント: