A cheap abstract class in ruby

Posted: 03/29/2009

When I create a class that I don’t want to allow anyone to instantiate, I use the following pattern:

  class MakeMeAbstract
    def initialize
      raise "Don't instantiate me!" if abstract_class?
      puts "Instantiated!"
    end
    private
    def abstract_class?
      self.class == MakeMeAbstract
    end
  end

It can’t be instantiated:

  MakeMeAbstract.new rescue puts "I'm abstract"   # => "I'm abstract"

But it can be subclassed, and the subclass can be instantiated:

  class Child < MakeMeAbstract
  end
  Child.new   # => "Instantiated!"

As a full disclaimer, this is a learning experience for me. When subclassing an abstract class I wonder if it would be better to use a mixin instead: I could overwrite mixed in methods just as easily as methods in a parent class. The structure changes from this:

  class Bar
    def status
      print "is full"
    end
  end
  class WetBar < Bar
    def status
      print "is wet, "
      super
    end
  end
  wet_bar = WetBar.new
  wet_bar.status    # => "is wet, is full"

To this:

  module Bar
    def status
      print "is full"
    end
  end
  class WetBar
    include Bar
    def status
      print "is wet, "
      super
    end
  end
  wet_bar = WetBar.new
  wet_bar.status    # => "is wet, is full"

Input is welcome in the comments.

About Me

I'm a skier, web developer, entrepreneur, freelancer, and all around stand-up guy living in Manhattan. This is me, repping one of my favorite shirts...

Follow me on twitter or send me an email.

All Posts

Music Blogs