💎

Rubyのmoduleについて with ChatGPT

2023/04/17に公開1

これはなに

  • Rubyのmoduleを作る機会があったので、ChatGPTに丁寧に解説してもらいました

問1:Ruby on Railsのソースコードを用いて、moduleの説明をしなさい

ChatGPTの解

本当に動くのか試してみた

module Wkwk
  def piyo
    puts 'hoge'
  end
end

class Hey
  include Wkwk
end

hey = Hey.new
hey.piyo
$ ruby module.rb
hoge

動きました。

  • クラスやmoduleで共通に使いたいメソッドをmoduleに集合させることができる
  • include モジュール名で、該当クラスで使えるようになる

ちなみに今回はmodelでこんな使い方をしました。

module HogeAccount
  extend ActiveSupport::Concern

  included do
    after_create :fill_hoge_account_id
  end

  def fill_hoge_account_id
    self.hoge_account_id = get_hoge_account_id
    self.save!
  end
end

class User < ApplicationRecord
  # hoge_account_id :integer
  include HogeAccount

  def get_hoge_account_id
    # HogeAccountモデルがリレーションであるとします
    self.hoge_account.id
  end
end

これでUserが新規作成されたタイミングで、Userモデルのhoge_account_idに、関連するHogeAccountモデルのidが登録できるようになりました!

問2: この内容を解説して

ChatGPTの解

本当に動くのか試してみた

名前の衝突が起こるケースはこんな感じだそうです。※一部変えてます

module HogeModule
  def hoge_method
    puts "ほげええええ"
  end
end

class HogeClass1
  include HogeModule

  def hoge_method
    puts "ほげくらすワン!"
  end
end

class HogeClass2
  include HogeModule

  def hoge_method
    puts "ほげくらすツー!"
  end
end

class1 = HogeClass1.new
class1.hoge_method

class2 = HogeClass2.new
class2.hoge_method

実行しました。

$ ruby  conflict_my_method.rb
ほげくらすワン!
ほげくらすツー!

moduleのhoge_methodに定義されたほげええええは表示されません。

正しい例で紹介されたソースコードを少し改変して作ります。

module HogeModule
  def hoge_method
    puts "ほげええええ"
  end

  module HogeClass1
    def hoge_method
      puts "ほげくらすワン!"
    end
  end

  module HogeClass2
    def hoge_method
      puts "ほげくらすツー!"
    end
  end
end

class HogeClass
  include HogeModule
end

class HogeClass1
  include HogeModule::HogeClass1
end

class HogeClass2
  include HogeModule::HogeClass2
end

my = HogeClass.new
my.hoge_method

class1 = HogeClass1.new
class1.hoge_method

class2 = HogeClass2.new
class2.hoge_method
$ ruby not_conflict_my_method.rb
ほげええええ
ほげくらすワン!
ほげくらすツー!

ほげええええを表示することができました!

まとめ

  • ChatGPTには「〇〇のソースコードを用いて」と伝えると正しい情報が得られることが多そう
  • 共通メソッドを作りたい時にはmoduleを使うととっても便利
  • 同じ名前で内容が異なる場合、module内にそれぞれ定義するとincludeの仕方で使い分けができる
  • concernで作るのが便利...という話はまた今度

おまけ

ChatGPTに「さらに」と伝えたらもっと詳しく教えてくれました。

ざっくり解説すると下記の感じ

  1. Mixinとしての利用
    • 既存の機能にクラスを追加する場合、サブクラスで継承せずともmoduleで新しいメソッドを追加できる
  2. 名前空間としての利用
    • 先で紹介した内容です
  3. モジュール関数の定義
    • self.hoge_methodでmodule内でメソッド名を定義すると、HogeModule.hoge_methodで呼び出せる
  4. moduleの継承
    • 親モジュールで定義されている内容を子モジュールにincludeできる
  5. moduleの拡張
    • クラスにmoduleをextendする事で、クラス呼び出し時にmoduleのメソッドを呼べるようになる
    hoge = HogeClass.new
    hoge.extend(HogeModule)
    hoge.hoge_method # => "ほげええええ"
    
  6. moduleの特異メソッド
    • これは3でいってた内容と同じだな?

あっているとこもあれば、なんか同じような事を繰り返し言ってたところもありました。

Discussion