続:クラスマクロ

http://d.hatena.ne.jp/UNKK/20110801/p1
こちらの記事の追記を読んでみて、なるほど自分が前回書いた例だと全てのクラスを汚染してしまう。

その点を踏まえて色々やっていたら、以下のようになった。
とはいっても、元記事のeigenclassメソッドをラムダに差し替えただけだが。

#!/usr/bin/env ruby
# -*- coding: utf-8 -*-

class Module
  def my_macro(arg)
    lambda{ class << self; self; end }.call.class_eval do
      define_method("Gorira" + arg.to_s) do
         "Gorira" + arg.to_s
      end
    end
  end
end

class C
  my_macro :x
end

puts C.Gorirax
#=> Gorirax

class D
end

puts D.Gorirax
#=> undefined method `Gorirax' for D:Class (NoMethodError)

自分の理解が浅いだけでもっといい方法あるのかも。