Railsのdelegateについて
delegate
オブジェクトの特定のメソッド呼び出しを別の関連オブジェクトに委譲することができる
例えば、以下のようにUserクラスと関連のあるProfileクラスがあり、Profileクラスにあるfull_nameというメソッドを使うには
user.profile.full_name と書くことになるが、delegateしておくとuser.full_name というような書き方ができる
code:ruby
class User < ApplicationRecord
has_one :profile
# Profileのメソッドを委譲
delegate :full_name, :bio, to: :profile
end
code:ruby
class Profile < ApplicationRecord
belongs_to :user
def full_name
end
end
allow_nil
関連オブジェクトが nil の場合に例外を防ぎ、nil を返す
code:ruby
class User < ApplicationRecord
has_one :profile
# allow_nil: true を指定
delegate :full_name, to: :profile, allow_nil: true
end
prefix
委譲されたメソッドにプレフィックスを追加する
code:ruby
class User < ApplicationRecord
has_one :profile
# prefix: true を指定
delegate :full_name, :bio, to: :profile, prefix: true
end
# prefix を付けた場合
# user.profile_full_name #=> "hana yamada" private
委譲されたメソッドをprivateメソッドにする
code:ruby
class User < ApplicationRecord
has_one :profile
# 委譲メソッドをプライベートに設定
delegate :full_name, to: :profile, private: true
end
delegate_missing_to
profileクラスの全てを委譲したい場合、delegate_missing_toを使う
code:ruby
class User < ApplicationRecord
has_one :profile
delegate_missing_to :profile
end