harp:~ > cat a.rb
class Module
def struct_attrs struct
singleton_class = class << self
self
end
singleton_class.module_eval{ struct.members.each{|m| attr_accessor m} }
end
end
class Bas
foo = Struct.new :attribute, :another_attribute
bar = foo.new
struct_attrs foo
end
Bas.attribute = "a value"
p Bas.attribute
harp:~ > ruby a.rb
"a value"
-a
···
On Sun, 12 Nov 2006, J2M wrote:
I would like to be able to be able to include instance methods of a
Struct into a class. e.g.
foo = Struct.new(:attribute, :another_attribute)
bar = foo.new
class Bas
some_ruby_magic
end
So that I can then do
Bas.attribute="a value"
Bas.attribute
Kind of like doing module_functions but that doesn't work inside a
class.
Thanks,
James
--
my religion is very simple. my religion is kindness. -- the dalai lama
I would like to be able to be able to include instance methods of a
Struct into a class. e.g.
foo = Struct.new(:attribute, :another_attribute)
bar = foo.new
class Bas
some_ruby_magic
end
So that I can then do
Bas.attribute="a value"
Bas.attribute
Kind of like doing module_functions but that doesn't work inside a
class.
Foo = Struct.new(:attribute, :another_attribute)
class Bas
extend Foo.to_module
end
Ha! Only if it were so easy! Actaully if one had access to Ruby's
source it would rather trivial (hint). In anycase to par down Ara's
solution to it's core:
Foo = Struct.new :attribute, :another_attribute
class Bas
class << self
attr_accessor *Foo.members
end
end
Note the use of the constant which eases access by avoiding
(class<<self;self;end).class_eval.
I got the final solution down to this which I think is rather elegant;
class Bas < Struct.new :attribute, :another_attribute
class << self
attr_accessor *Bas.members
end
end
class Bas < Struct.new :attribute, :another_attribute
class << self
attr_accessor *members
end
end
Do you realize that you are adding #attribute and #another_attribute at
both the instance level and the class level, and niether will reference
tha same values? I.e.
Do you realize that you are adding #attribute and #another_attribute at
both the instance level and the class level, and niether will reference
tha same values? I.e.
I got the final solution down to this which I think is rather elegant;
class Bas < Struct.new :attribute, :another_attribute
class << self
attr_accessor *Bas.members
end
end
class Bas < Struct.new :attribute, :another_attribute
class << self
attr_accessor *members
end
end
Do you realize that you are adding #attribute and #another_attribute at
both the instance level and the class level, and niether will reference
tha same values? I.e.
Also, what is the point in creating a Struct in this case when you're
basically only using member names?
robert
Good spot :-/
I started out using Struct as I wanted the extra methods for free and
was creating instances off of it. I have just re-worked this and just
mix enumerable into the class and get most of what I got from struct,
so have strayed quite a way from the original question.