I've come across a number of occasions where methods like
#class_attr_accessor, or #module_alias_method are defined. It's nice
to have those, but it seems to me this isn't very DRY since the
methods for these things already exist in the class domain (ie.
singleton class). So what do others think of this instead:
module Kernel
# Provides access to an object's metaclass (singleton class)
# by-passing access provisions. So for example:
···
#
# class X
# meta.attr_accesser :a
# end
#
# X.a = 1
# X.a #=> 1
def meta
@_meta_functor ||= Functor.new do |op,*args|
(class << self; self; end).__send__(op,*args)
end
end
end
Personally, I've wished I could name the method #class and/or #module,
but obviously that's not doable. In any case, do you think this is a
better approach? Are there any serious disadvantages to it? Or do you
prefer a myriad of special class level methods? If so why?
If you are not familiar with Facets Functor, it's your basic higher
order message:
class Functor
# Privatize all methods except vital methods and #binding.
private(*instance_methods.select { |m| m !~ /(^__|^binding$)/ })
def initialize(&function)
@function = function
end
def to_proc
@function
end
# Any action against the functor is processesd by the function.
def method_missing(op, *args, &blk)
@function.call(op, *args, &blk)
end
end
Thanks,
T.