Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

メタプログラミングRuby | 魔術 | ブランクスレート

概要

ブランクスレート

内容

ブランクスレート => blank slate => 白紙の意。
method_missingを利用したゴーストメソッドを実装する際などに
邪魔になる基底クラスのメソッドなどをすべて非定義の状態にすることで
メソッド名の衝突を避ける手法。

サンプル

# encoding: utf-8
require "pp"

# ゴーストメソッドで指定したメソッド名と引数を出力する
class Hoge
  def method_missing(name, *args)
    puts "method name = #{name}"
    puts "args = #{args}" if args.size != 0
  end
end

puts Hoge.new.hoge "hige"
puts Hoge.new.inspect  # Object#inspectが呼び出される

# ブランクストレートでObjectやKernelt等のメソッドを非定義にする
class Hoge
  instance_methods.each do |m|
    undef_method m unless m.to_s =~ /method_missing|respond_to?|^__|object_id/
  end
end

puts Hoge.new.inspect # Hoge#method_missing内の処理が呼び出される

出力

method name = hoge
args = ["hige"]

#<Hoge:0x29773f8>
method name = inspect