method_missing [ruby]

method_missing

Module#undef_methodとModule#remove_method

リファクタリング

 #元のコード。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
  #今回method_missingで呼び出したいメソッドが親クラスなどに定義されていると困るので、それに対応
  instance_methods.each do |method|
    undef_method method unless method.to_s =~ /method_missing|respond_to¥?|^__.+__$/
  end

  def intialize(computer_id, data_source)
    @id = computer_id
    @data_source = data_source
  end

  def respond_to?(method)
    @data_source.respond_to?("get_#{method}_info") || super
  end

  def method_missing(name, *args)
    super unless @data_source.renspond_to?("get_#{name}_info)

    info = @data_source.__send__("get_#{name}_info", @id)
    price = @data_source.__send__("get_#{name}_price", @id)
    result = "#{name.capitalize} : #{info}, #{price}"
    end
  end

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

メタプログラミングRuby

メタプログラミングRuby