On Mon, Feb 03, 2003 at 06:23:35AM +0900, Tom Sawyer wrote:
> On Sunday 02 February 2003 09:01 am, Mauricio FernŠŌdez wrote:
> 
> > Now comes the important question: why do you need that?
> 
> in my case it is because i have a class that gets some dynamically created 
> methods based on whether or not certain criteria are met. if it is then these 
> methods need to be non-overridable, if not then the methods defined in the 
> subclasses can be used. i now that there's surly other ways to deal with 
> this, but it occured to me the have methods that can't be overrided was one 
> way to do it and i was wondering if it could be done....and sure enough!

I've been thinking on how to make this ressilient even to malicious
attempts to redefine things (I guess one possible application would be
creating a sandbox for rubyrobots or such).

It turns out it is quite easy to break as it stands:

class D < A
  class << self
    def method_added id
    end
  end
  def a; puts "I won!"; end
end

D.new.a   # ==> "I won!"

So here's the fix:

module NoOverloading
  def inherited << sub
    def method_added(id)
      return if __no_redef_list__.index(id) == nil
      remove_method id
    end
    self.freeze
  end
end

A.freeze
NoOverloading.freeze

this makes absolutely impossible to redefine #a, AFAIK. However, it also
means that you can no longer create class methods.

Something more elegant would have been

module NoOverloading
  def inherited sub
    class << sub
      class << self
        # the singleton's singleton class!!!
        def method_added id
          remove_method id if id == :method_added
        end
        self.freeze
      end
    end
    def method_added(id)
      return if __no_redef_list__.index(id) == nil
      remove_method id
    end
  end
end

But this doesn't work as it seems the singleton's singleton method method_added is 
not called when a new singleton method is added.

Now, what are singletons' singletons useful for? 
-- 
 _           _                             
| |__   __ _| |_ ___ _ __ ___   __ _ _ __  
| '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ 
| |_) | (_| | |_\__ \ | | | | | (_| | | | |
|_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
	Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com

* Linux Viruscan.....
  Windows 95 found.  Remove it? (Y/y)
	-- Unknown source