私はRuby1.9.2とRubyonRailsv3.2.2gemを使用しています。私はメタプログラミングを「正しい方法」で学ぼうとしています。現時点では、RoRモジュールによって提供されるブロックのインスタンスメソッドをエイリアスしています。included do ... end
ActiveSupport::Concern
module MyModule
extend ActiveSupport::Concern
included do
# Builds the instance method name.
my_method_name = build_method_name.to_sym # => :my_method
# Defines the :my_method instance method in the including class of MyModule.
define_singleton_method(my_method_name) do |*args|
# ...
end
# Aliases the :my_method instance method in the including class of MyModule.
singleton_class = class << self; self end
singleton_class.send(:alias_method, :my_new_method, my_method_name)
end
end
「初心者」と言えば、Webで検索してステートメントを思いつき、変数のスコープを設定するために(ブロックsingleton_class = class << self; self end
の代わりに)それを使用して、エイリアシングを動的に生成しました。class << self ... end
my_method_name
上記のコードで機能する理由と方法を正確に理解しsingleton_class
、同じものを実装するためのより良い方法(おそらく、より保守可能でパフォーマンスの高い方法)があるかどうか(エイリアシング、シングルトンメソッドの定義など)を理解したいと思いますが、 "そうではないと思うので。