Provides a module that may be included in a Ruby class, that protects the constructor; good for enforcing instantiation of classes using, for instance, a class factory. The code itself is not mine, I just wrapped it in a gem and provided the examples; sorry, I don't remember the origin of the code to give credit. :S
MIT License
Provides a module that may be included in a Ruby class, that protects the constructor; good for enforcing instantiation of classes using, for instance, a class factory. The code itself is not mine, I just wrapped it in a gem and provided the examples; sorry, I don't remember the origin of the code to give credit.
Add this line to your application's Gemfile:
gem 'ProtectedConstructor'
And then execute:
$ bundle
Or install it yourself as:
$ gem install ProtectedConstructor
require 'protected_constructor'
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
git checkout -b my-new-feature
)git commit -am 'Add some feature'
)git push origin my-new-feature
)