【Ruby】delegateの便利オプションallow_nil,prefix
TL;DR
allow_nil
でNoMethodError
対策prefix
でメソッド名に接頭辞をつける
delegateの便利オプション
allow_nil
class User include ActiveMode::Model attr_accesor :profile delegate :name, to: :profile, allow_nil: true end class Profile attr_accessor :name end
メソッド呼び出し時にターゲット(この場合はprofile
)がnilの場合はnilを返してくれるようになる.
NoMethodError
がraiseされなくなるのでuser.try(:name)
とかしなくてもよくなる.
prefix
class Event include ActiveMode::Model attr_accesor :name, :location delegate :name, to: :location, prefix: true end class Location include ActiveMode::Model attr_accesor :name end
メソッド名にprefixが付くようになる.true
の場合はターゲット名,文字列を渡した場合は当該文字列がprefixとなる(この場合はEvent#location_name
が生えてくる).
元クラスが既に同名メソッドを持つ場合などに良い.