【发布时间】:2012-10-17 14:56:31
【问题描述】:
我正在使用 Ruby 1.9.2 和 Ruby on Rails v3.2.2 gem。我正在尝试以“正确的方式”学习元编程,此时我正在为 RoR ActiveSupport::Concern 模块提供的 included do ... end 块中的 instance 方法设置别名:
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
“新手”说,通过网络搜索,我想出了singleton_class = class << self; self end 语句,我使用它(而不是class << self ... end 块)为了范围@987654327 @变量,使别名动态生成。
我想准确了解 为什么 和 如何 singleton_class 在上面的代码中工作,以及是否有更好的方法(也许,更易于维护和性能更好)一)实现相同(别名,定义单例方法等),但“正确的方式”,因为我认为不是这样。
【问题讨论】:
标签: ruby-on-rails ruby methods metaprogramming definition