Understanding the singleton class when aliasing a instance method
Posted
by
Backo
on Stack Overflow
See other posts from Stack Overflow
or by Backo
Published on 2012-10-17T14:56:31Z
Indexed on
2012/10/17
23:01 UTC
Read the original article
Hit count: 198
I am using Ruby 1.9.2 and the Ruby on Rails v3.2.2 gem. I am trying to learn Metaprogramming "the right way" and at this time I am aliasing an instance method in the included do ... end
block provided by the RoR ActiveSupport::Concern
module:
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
"Newbiely" speaking, with a search on the Web I came up with the singleton_class = class << self; self end
statement and I used that (instead of the class << self ... end
block) in order to scope the my_method_name
variable, making the aliasing generated dynamically.
I would like to understand exactly why and how the singleton_class
works in the above code and if there is a better way (maybe, a more maintainable and performant one) to implement the same (aliasing, defining the singleton method and so on), but "the right way" since I think it isn't so.
© Stack Overflow or respective owner