LoginSignup
2
1

More than 5 years have passed since last update.

delegateについて

Posted at

delegateとは

あるメソッドの処理を他のメソッドに任せることができる

delegateのメリット

書く文字が少なくなる

コーディングする際に、書く量を減らせます

以下のような場合。。。。

book.rb
#t.string :title
#t.integer :author_id
belongs_to :author
author.rb
#t.string :name
has_many :books

こんな風にかくと。。。。

book.rb
#t.string :title
#t.integer :author_id

belongs_to :author
delegate :name, to: :author

author.rb
#t.string :name
has_many :books

コンソール上でこんなことができます。

#コンソール

$book = Book.first
$book.name
#=> authorのインスタンスからnameの情報をとることができる


メソッドを再利用できる

def fuga
 fuga
end


def hoge
 hogehogehoge
 hogehogehoge
 hogehogehoge
 ・・・・・・・・
end

delegate :fuga, to: :hoge

このようにメソッドが二つあり、一つが(今回はhoge)めちゃくちゃ難しいメソッドの時とかでも、
hogeメソッドを完全理解せずとも、メソッドの再利用ができます。

delegateをちょろっと解剖

delegateを使わず同じ機能を実装するとなると、下のようになります。
book.rbにdelegate :name , to: :author書く場合は、代わりに下のようにかけます。

book.rb
belongs_to :author
def name
  author.name
end
author.rb
has_many :books

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1