Struct-like behaviour in custom classes

  • Thread starter Levin Alexander
  • Start date
L

Levin Alexander

Hi,

How can I build a Class that works like the built-in "Struct" and returns=
=20
new anonymous classes based on arguments to MyClass.new?

A simplified example:

with_foo =3D MyClass.new:)foo)
one =3D with_foo.new
one.foo

with_bar =3D MyClass.new:)bar)
two =3D with_bar.new
two.bar

I tried to do:

class MyClass
def self.new_class(method_name)
c =3D Class.new(self)
c.class_eval do
define_method(method_name) { puts "method #{method_name} called" }
end
return c
end
end

How can I rename 'new_class' to 'new' without breaking 'new' in derieved =
=20
classes?

Thank You,
Levin
 
P

Pit Capitain

Levin said:
How can I build a Class that works like the built-in "Struct" and
returns new anonymous classes based on arguments to MyClass.new?

A simplified example:

with_foo = MyClass.new:)foo)
one = with_foo.new
one.foo

with_bar = MyClass.new:)bar)
two = with_bar.new
two.bar

I tried to do:

class MyClass
def self.new_class(method_name)
c = Class.new(self)
c.class_eval do
define_method(method_name) { puts "method #{method_name} called" }
end
return c
end
end

How can I rename 'new_class' to 'new' without breaking 'new' in
derieved classes?

Hi Levin,

you have to redefine "new" in the anonymous classes to call the original
Class.new method. One possibility is to use aliases:

class MyClass
class << self
alias :eek:rg_new :new
def new(method_name)
Class.new(self) do
class << self
alias :new :eek:rg_new
end
define_method(method_name) do
puts "method #{method_name} called"
end
end
end
end
end

Regards,
Pit
 
L

Levin Alexander

Pit Capitain said:
you have to redefine "new" in the anonymous classes to call the origina= l =20
Class.new method. One possibility is to use aliases:

class MyClass
class << self
alias :eek:rg_new :new
def new(method_name)
Class.new(self) do
class << self
alias :new :eek:rg_new
end
define_method(method_name) do
puts "method #{method_name} called"
end
end
end
end
end

Thank you, that works great.

-Levin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,709
Latest member
AustinMudi

Latest Threads

Top