Module: Final

Defined in:
lib/final.rb

Overview

Make your class final. Once final’ized, it cannot be subclassed and its methods cannot be redefined.

Defined Under Namespace

Classes: Error

Constant Summary collapse

VERSION =

The version of the final library.

'0.1.2'

Class Method Summary collapse

Class Method Details

.included(mod) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/final.rb', line 11

def self.included(mod)
  # Store already defined methods.
  mod.instance_eval("@final_methods = []")

  # Internal accessor used in the method_added definition.
  def mod.final_methods
    @final_methods
  end

  # Prevent subclassing, except implicity subclassing from Object.
  def mod.inherited(sub)
    raise Error, "cannot subclass #{self}" unless self == Object
  end

  # Prevent methods from being redefined.
  #--
  # There's still going to be a method redefinition warning. Gosh, it
  # sure would be nice if we could disable warnings.
  #
  def mod.method_added(sym)
    if final_methods.include?(sym)
      raise Error, "method '#{sym}' already defined"
    else
      final_methods << sym
    end
  end
end