Ed de Almeida Ed de Almeida - 22 days ago 7
Ruby Question

Error in initialize when creating a class dynamically

I receive some paramters at the command line. The first one of them tells me what kind of uby object I must create to perform de desired action. I store this parameter in

@entity
and then I create an instance of this class by doing

entity_class = "EmeraldFW::#{@entity.capitalize}".split('::').inject(Object) {|o,c| o.const_get c}
entity_instance = entity.new(@arguments,@options)
entity_instance.execute_command


I am geting an error when I try to create one of these instances, say Project.

My project class is

module EmeraldFW

class Project < EmeraldFW::Entity

def self.initialize(args,opts)
@valid_option = [ :language, :test, :database, :archetype ]
super(args,opts)
end
.
.
.


and my class Entity is

module EmeraldFW

class Entity

attr_accessor :entity_type, :valid_commands

def self.initialize(args,opts)
@args = args
@opts = clean_option(opts)
end

.
.
.


My error is

/home/edvaldo/software/github/emeraldfw21/lib/emeraldfw.rb:41:in `initialize': wrong number of arguments (given 2, expected 0) (ArgumentError)


and I don't know why this is happening. As you may see, initialize receives two arguments and I gave it two arguments, as required.

Maybe because I'm looking at this for a long time, but I just can't see the reason. Would somebody help me?

Answer

It is because your initialize method is written as "class" method (class' singleton method), whereas it should be an instance method. Due to that fact original initialize method which you are calling with new:

entity_instance = entity.new(@arguments,@options)

takes no arguments.

To resolve the issue remove self. parts from self.initialize method definitions.


class Foo
  def initialize(bar, baz)
    @bar = bar
    @baz = baz
  end
end

Foo.new(:bar, :baz)
#=> #<Foo:0x007fa6d23289a0 @bar=:bar, @baz=:baz>
Comments