Module: ProtectedConstructor

Defined in:
lib/ProtectedConstructor.rb,
lib/ProtectedConstructor/version.rb

Overview

Examples:

require 'ProtectedConstructor'

class Klass
  include ProtectedConstructor

  def initialize
  end
end

module KlassFactory
  class << self
    public
    def create
      Klass.send(:new)
    end
  end
end

# Constructor is not protected.
klass = Klass.new # NoMethodError

# Example using factory...
klass = KlassFactory::create # works
klass.nil? # false
klass.is_a?(Klass) # true

# Example just using #send...
klass = Klass.send(:new) # works
klass.nil? # false
klass.is_a?(Klass) # true

Constant Summary collapse

VERSION =
"1.0.0"

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/ProtectedConstructor.rb', line 36

def self.included(klass)
  klass.module_eval do
    class << self
      protected :new

      def inherited(klass)
        klass.module_eval do
          def self.new(*args); super; end
        end
      end
    end
  end
end