Augmented Usamimi

it { is_expected.to be_blog.written_by(izumin5210) }

【Ruby】delegateの便利オプションallow_nil,prefix

TL;DR

  • allow_nilNoMethodError対策
  • 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が生えてくる). 元クラスが既に同名メソッドを持つ場合などに良い.