Data for eigenclass

  • Thread starter Jari Williamsson
  • Start date
J

Jari Williamsson

How do I set data at the eigenclass level (data should basically be
connected to the class name)?

The @@my_data syntax seems to attach only to the original class in which
it was defined, not for any subclasses. And the @my_data syntax attach
to each instance.

I think I should be able to solve it "manually" with a hash, but I'm
looking for a built-in syntax for it?


Best regards,

Jari Williamsson
 
T

Thomas Wieczorek

The @@my_data syntax seems to attach only to the original class in which
it was defined, not for any subclasses. And the @my_data syntax attach
to each instance.

I am not sure if I understand you. Class variables(@@bar) are
available for its children:
(in irb)
class Foo
@@foo = "Yeehaaw!"
end
class Bar < Foo
def initialize
puts @@foo
end
end
=> "Yeehaaw!"
 
T

tho_mica_l

The @@my_data syntax seems to attach only to the original class in which
it was defined, not for any subclasses.

You can use attributes (@var) at the class level and manually copy
values with the Class#inherited method.

class A
class << self
attr_accessor :foo
def inherited(sub)
sub.foo = @foo
end
end
self.foo = 1
end

class B < A
end

p A.foo, B.foo
# => [1, 1]
B.foo = 2
p A.foo, B.foo
# => [1, 2]

If something like this is what you were asking for.

Or you could use some package that does this for you. IIRC traits
implements such a thing.

Thomas.
 
J

Jari Williamsson

tho_mica_l said:
The @@my_data syntax seems to attach only to the original class in which
it was defined, not for any subclasses.

You can use attributes (@var) at the class level and manually copy
values with the Class#inherited method.

class A
class << self
attr_accessor :foo
def inherited(sub)
sub.foo = @foo
end
end
self.foo = 1
end

class B < A
end

p A.foo, B.foo
# => [1, 1]
B.foo = 2
p A.foo, B.foo
# => [1, 2]

If something like this is what you were asking for.

Thanks! This was what I was looking for!
Or you could use some package that does this for you. IIRC traits
implements such a thing.

I'll look at it as well!


Best regards,

Jari Williamsson
 
R

Rados³aw Bu³at

PiA+IEkgYW0gbm90IHN1cmUgaWYgSSB1bmRlcnN0YW5kIHlvdS4gQ2xhc3MgdmFyaWFibGVzKEBA
YmFyKSBhcmUKPiA+IGF2YWlsYWJsZSBmb3IgaXRzIGNoaWxkcmVuOgo+IE5vIGxvbmdlciBpbiBS
dWJ5I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G1lOgoKQzpcPnJ1YnkgLXYKcnVieSAxLjguNiAo
MjAwNy0wMy0xMyBwYXRjaGxldmVsIDApIFtpMzg2LW1zd2luMzJdCgpDOlw+cnVieSAtZSAiY2xh
c3MgQTsgQEBhPTE7IHB1dHMgQEBhOyBlbmQ7IGNsYXNzIEIgPCBBOyBwdXRzIEBAYSBlbmQiCjEK
MQo=
 

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

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top