動的メソッドと動的ディスパッチ [ruby]

動的ディスパッチとは

動的メソッドとは

  • メソッドを動的に定義すること。
  • 具体的には、define_methodを使う。

上記2つを活用したリファクタリング

 #元のコード。data_sourceにある機器情報を取得し、出力するクラス
class Computer
  def intialize(computer_id, data_source)
    @id = computer_id
    @data_source = data_source
  end

  def mosce
    info = data_source.get_mouse_info(@id)
    price = data_source.get_mouse_price(@id)
    result = "Mouse : #{info}, #{price}"
  end

  def display
    info = data_source.get_display_info(@id)
    price = data_source.get_mouse_price(@id)
    result = "Display : #{info}, #{price}"
  end

  #以下同様のコードが続く
end

#リファクタリング
class Computer
  def intialize(computer_id, data_source)
    @id = computer_id
    @data_source = data_source
   
    @data_source.methods.grep(/^get_(.+)_info$/){|item| Computer.define_component(item)}
  end

  def self.define_component(name)
    define_method(name) do #動的メソッド
      info = data_source.__send__("get_#{name}_info", @id) #動的ディスパッチ
      price = data_source.__send__("get_#{name}_price", @id)
      result = "#{name.capitalize} : #{info}, #{price}"
    end
  end
end

参照:メタプログラミングRuby

メタプログラミングRuby

メタプログラミングRuby