Robert Klemme
11/12/2006 1:28:00 PM
dblack@wobblini.net wrote:
> Hi--
>
> On Sun, 12 Nov 2006, Robert Klemme wrote:
>
>> 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.
>>
>> I don't know why people make it so complicated. :-) All these are
>> easier than other approaches suggested so far:
>>
>> Foo = Struct.new(:attribute, :another_attribute)
>> class Bas < Foo
>> end
>>
>> class Bas < Struct.new(:attribute, :another_attribute)
>> end
>>
>> or even
>>
>> Bas = Struct.new(:attribute, :another_attribute) do
>> def another_method() end
>> end
>
> You're adding instance methods to Bas rather than to Bas's singleton
> class, though. The OP wants to do:
>
> Bas.attribute = "a value"
Oh, ok then I misinterpreted that. I read "include instance methods
into a class" as including them as instance methods. My bad. Sorry for
the noise.
In this particular case, /if/ the aim is to define attribute accessors a
direct definition is probably the easiest solution
class Bas
class <<self
attr_accessor :attribute, :another_attribute
end
end
Regards
robert