Robert Klemme
3/22/2008 1:39:00 PM
On 22.03.2008 14:15, Trans wrote:
> 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.
I am feeling stupid because I seem to overlook something: what is the
advantage of your approach vs.
class Object
def meta
class<<self;self;end
end
end
? As far as I can see your functor in this case simply delegates all
method invocations to the singleton class. Why not directly use /
return it?
While I think about it you could even do:
class Object
def meta(&b)
cl = class<<self;self;end
cl.class_eval(&b) if b
cl
end
end
class Some
meta do
attr_accessor :foo
def incr
self.foo += 1
end
end
end
Kind regards
robert