Forum: Ruby class design

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0ed1fc95a73b8626b25b6806ed7497f1?d=identicon&s=25 Spitfire (Guest)
on 2006-12-25 20:56
(Received via mailing list)
How do I design a class such that it can never be instantiated? Say
for example a class containing static members alone, which requires no
instantiation!
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2006-12-25 21:02
(Received via mailing list)
On 25.12.2006 20:54, Spitfire wrote:
>   How do I design a class such that it can never be instantiated? Say
> for example a class containing static members alone, which requires no
> instantiation!

You can apply some tactics to make it harder but AFAIK there is no safe
way to completely prevent instantiation.  Typically something like this
will suffice

class Foo
   def self.new(*a,&b) raise "Must not instantiate!" end
end

irb(main):004:0> Foo.new
RuntimeError: Must not instantiate!
         from (irb):2:in `new'
         from (irb):4
         from :0

Other than that you can also use module Singleton, which is probably
better documentation wise:

irb(main):005:0> require 'singleton'
=> true
irb(main):006:0> class Bar
irb(main):007:1> include Singleton
irb(main):008:1> end
=> Bar
irb(main):009:0> Bar.new
NoMethodError: private method `new' called for Bar:Class
         from (irb):9
         from :0

Kind regards

	robert
4299e35bacef054df40583da2d51edea?d=identicon&s=25 James Gray (bbazzarrakk)
on 2006-12-25 21:04
(Received via mailing list)
On Dec 25, 2006, at 1:55 PM, Spitfire wrote:

>   How do I design a class such that it can never be instantiated?
> Say for example a class containing static members alone, which
> requires no instantiation!

Just use a module for this:

module Static
   # ... defined constants and methods here ...
end

James Edward Gray II
This topic is locked and can not be replied to.