From: Josh Cheek Date: 2012-08-19T15:26:18+09:00 Subject: Re: A Ruby class is never closed --f46d041827526cc43b04c79878dd Content-Type: text/plain; charset=ISO-8859-1 On Thu, Aug 16, 2012 at 12:59 PM, Jan E. wrote: > What you do mean? A sealed class like in C# which doesn't allow > subclasses? Or the singleton pattern where a class can only be > instantiated once? > > You can actually do both. For a sealed/final class you can use the > "inherited" hook which gets called every time a new class is derived > from this class. If it raises an error, the class is "sealed" (the > question is if this makes sense). > > class A > def self.inherited subclass > raise "cannot derive from sealed class #{self}" > end > end > > # this doesn't work > class B < A; end > > For the singleton pattern, there's the singleton module in the standard > library. > > -- > Posted via http://www.ruby-forum.com/. > > I can't think of any reason you would want to do this, but I don't think you can ever *force* this sort of situation. e.g. if I decided that I wanted to subclass it, I could just do this class << A remove_method :inherited end I'd look very skeptically at any piece of code which did had such a hook, though. --f46d041827526cc43b04c79878dd Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable On Thu, Aug 16, 2012 at 12:59 PM, Jan E. <lists@ruby-forum.com><= /span> wrote:
What you do mean? A sealed class like in C# which doesn't allow
subclasses? Or the singleton pattern where a class can only be
instantiated once?

You can actually do both. For a sealed/final class you can use the
"inherited" hook which gets called every time a new class is deri= ved
from this class. If it raises an error, the class is "sealed" (th= e
question is if this makes sense).

class A
=A0 def self.inherited subclass
=A0 =A0 raise "cannot derive from sealed class #{self}"
=A0 end
end

# this doesn't work
class B < A; end

For the singleton pattern, there's the singleton module in the standard=
library.

I can't think of any reason you woul= d want to do this, but I don't think you can ever *force* this sort of = situation. e.g. if I decided that I wanted to subclass it, I could just do = this

class << A
=A0 remove_method :inherited
end

I'd = look very skeptically at any piece of code which did had such a hook, thoug= h.
--f46d041827526cc43b04c79878dd--