ここで簡単な例を考えてみましょう。
class Base
  @tag = nil 
  def self.tag(v = nil) 
    return @tag unless v 
    @tag = v
  end 
end 
class A < Base 
  tag :A
end
class B < Base
  tag :B
end 
class C < Base; end
puts "A: #{A.tag}"
puts "B: #{B.tag}"
puts "A: #{A.tag}"
puts "C: #{C.tag}"
期待どおりに機能します
A: A
B: B 
A: A
C: 
ベースが拡張されて同じ機能を提供するが、クラスによって指定されたすべてのタグ情報を持つモジュールを作成したいと思います。例えば。
module Tester 
  def add_ident(v); ....; end
end
class Base 
  extend Tester 
  add_ident :tag
end 
私はまっすぐな評価でそれを行うことができることを発見したので、:
def add_ident(v)
  v = v.to_s 
  eval "def self.#{v}(t = nil); return @#{v} unless t; @#{v} = t; end"
end
しかし、私はどの言語でもeval文字列を使用するのは本当に嫌いです。
evalを使用せずにこの機能を取得する方法はありますか?私はdefine_methodとinstance_variable_get/setのすべての組み合わせを考えてきましたが、それを機能させることができません。
RailsなしのRuby1.9。