Sha256: 64054b196ba5a5a0b8daf31824f05d2c5c52cc54fed6607a87ebf38b6f84a702

Contents?: true

Size: 926 Bytes

Versions: 2

Compression:

Stored size: 926 Bytes

Contents

require "ProtectedConstructor/version"

# @example
#   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 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
#
module ProtectedConstructor
  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
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ProtectedConstructor-2.0.0 lib/ProtectedConstructor.rb
ProtectedConstructor-1.0.5 lib/ProtectedConstructor.rb