gangelo
gangelo

Reputation: 3182

Want to instantiate a ruby class using a private constructor from factory

I am used to c#/.net, so I come form a typesafe background. I am using Ruby. I want to create a class (ClassA) that has a private (I'd settle for protected if I need to) constructor. The reason being, I want to create a Factory (FactoryModule::create) that controls the instantiation of all ClassA objects. I realize this is not fool-proof(?) in Ruby, but at least the code will be self-documenting in that it will be obvious based on the code and the tests that ClassA must be instantiated via the FactoryModule::create method. In the ModuleFactory::create method, I tried changing the visibility of the ClassA constructor to public, instantiating the object, then changing the visibility back to private but A) I received errors and B) it is sloppy and not thread-safe. Any thoughts?

Update Answer:

https://gist.github.com/gangelo/5551902

Upvotes: 0

Views: 749

Answers (2)

gangelo
gangelo

Reputation: 3182

Update: Answer

Including this module in my class, protects Klass.new from being called:

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

Instantiating Klass via protected constructor, takes place as such:

Klass.send(:new, *params...*)

Credit for this solution can be found: here

Upvotes: 0

theTRON
theTRON

Reputation: 9649

If you want to call a private (or protected) method from outside of your class, you can use send. So in your factory you could have something like:

instance = ClassA.send(:create)

Upvotes: 1

Related Questions