Module: AbstractClass

Defined in:
lib/abstract_class.rb,
lib/abstract_class/version.rb,
lib/abstract_class/test_helper.rb

Overview

Adds the ability to declare classes as abstract so that they can’t be instantiated or allocated

Defined Under Namespace

Modules: TestHelper, Version

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object

When included, it will alias_method_chain allocate and new methods with :abstract_class in klass



7
8
9
10
11
12
13
14
15
# File 'lib/abstract_class.rb', line 7

def self.included(klass)
  klass.class_eval do
    alias_method :allocate_without_abstract_class, :allocate
    alias_method :allocate, :allocate_with_abstract_class

    alias_method :new_without_abstract_class, :new
    alias_method :new, :new_with_abstract_class
  end
end

Instance Method Details

#abstractObject

Declares this class as abstract and prevents it from being instantiated or allocated



18
19
20
# File 'lib/abstract_class.rb', line 18

def abstract
  @abstract = true
end

#abstract?Boolean

Checks if this class has been declared as abstract

Returns:

  • (Boolean)


23
24
25
# File 'lib/abstract_class.rb', line 23

def abstract?
  @abstract ||= false
end

#allocate_with_abstract_classObject

Raises RuntimeError if class is abstract, otherwise returns allocate_without_abstract_class



28
29
30
# File 'lib/abstract_class.rb', line 28

def allocate_with_abstract_class
  abstract? ? raise("abstract class #{self} can't be allocated") : allocate_without_abstract_class
end

#new_with_abstract_class(*args, &block) ⇒ Object

Raises RuntimeError if class is abstract, otherwise returns new_without_abstract_class



33
34
35
# File 'lib/abstract_class.rb', line 33

def new_with_abstract_class(*args, &block)
  abstract? ? raise("abstract class #{self} can't be instantiated") : new_without_abstract_class(*args, &block)
end