From: Logan Capaldo Date: 2006-05-12T08:18:11+09:00 Subject: Re: final/closed classes in Ruby (was: Sharp knives and glue) On May 11, 2006, at 5:27 PM, Berger, Daniel wrote: > The 'Sharp knives and glue' thread inspired this. It's probably been > done before but here's my implementation of a final and/or closed > class: > > # Make a class unsubclassable > class Class > def final(klass) > class << klass > def inherited(subclass) > error = "Illegal attempt to subclass #{self} with > #{subclass}" > raise RuntimeError, error > end > end > end > end > > class Foo > final(self) # No subclasses allowed > end > > # Boom! > class Bar < Foo > end Has potential, but why not just do: class Class def final # or even final! class << self def inherited(subclass) error = "Illegal attempt to subclass #{self} with #{subclass}" raise RuntimeError, error end end end end class Foo final end class Bar < Foo end RuntimeError: Illegal attempt to subclass Foo with Bar from (irb):7:in `inherited' from (irb):17 Unfortunately, it raises an exception way too late. try: class Foo final end begin class Bar < Foo end # Foo.inherited(Bar) pretty much happens here rescue end b = Bar.new