Ajedi32
Ajedi32

Reputation: 48418

In Ruby, how do I implement a class whose new method creates subclasses of itself?

In Ruby, the Struct class's new method creates a subclass of Struct that behaves differently based on the parameters passed to it. How do I do something similar with my own class in Ruby? (I would have just copied Struct's source code, except it's written in C.)

irb(main):001:0> Foo = Struct.new(:foo, :bar)
=> Foo
irb(main):002:0> x = Foo.new
=> #<struct Foo foo=nil, bar=nil>
irb(main):003:0> Foo.superclass
=> Struct

Upvotes: 2

Views: 321

Answers (1)

sawa
sawa

Reputation: 168199

class A
  def self.new; Class.new(self) end
end

A.new # => #<Class:0x007f009b8e4200>

Edit This might better fit the OP's intention.

class A
  singleton_class.class_eval{alias :old_new :new}
  def self.new
    Class.new(self){singleton_class.class_eval{alias :new :old_new}}
  end
end

Upvotes: 3

Related Questions