[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Struct-like behaviour in custom classes

Levin Alexander

7/7/2005 4:38:00 PM

Hi,

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?

Thank You,
Levin


2 Answers

Pit Capitain

7/7/2005 9:00:00 PM

0

Levin Alexander schrieb:
> 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 :org_new :new
def new(method_name)
Class.new(self) do
class << self
alias :new :org_new
end
define_method(method_name) do
puts "method #{method_name} called"
end
end
end
end
end

Regards,
Pit


Levin Alexander

7/8/2005 12:40:00 PM

0

Pit Capitain <pit@capitain.de> wrote:

> 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 :org_new :new
> def new(method_name)
> Class.new(self) do
> class << self
> alias :new :org_new
> end
> define_method(method_name) do
> puts "method #{method_name} called"
> end
> end
> end
> end
> end

Thank you, that works great.

-Levin