[Code] Creating attr like methods
-
I have a set of classes where I'd like to use attr like syntax to define some properties for each class. Each of these classes inherit from a base class. I was wondering if it was possible to define your own attr like syntax?
<span class="syntaxdefault">class Hello </span><span class="syntaxkeyword"><</span><span class="syntaxdefault"> MyBaseClass<br /> foo</span><span class="syntaxkeyword">(</span><span class="syntaxdefault"> </span><span class="syntaxkeyword">;</span><span class="syntaxdefault">lorem</span><span class="syntaxkeyword">,</span><span class="syntaxdefault"> </span><span class="syntaxkeyword">;</span><span class="syntaxdefault">ipsum </span><span class="syntaxkeyword">)<br /></span><span class="syntaxdefault">end<br /></span>
The simple solution:
<span class="syntaxdefault">class MyBaseClass<br /> private </span><span class="syntaxcomment"># Not required, but I like to scope'em.<br /></span><span class="syntaxdefault"> def self</span><span class="syntaxkeyword">.</span><span class="syntaxdefault">foo</span><span class="syntaxkeyword">(</span><span class="syntaxdefault"> </span><span class="syntaxkeyword">*</span><span class="syntaxdefault">args </span><span class="syntaxkeyword">)<br /></span><span class="syntaxdefault"> </span><span class="syntaxcomment"># Do magic stuff!<br /></span><span class="syntaxdefault"> end<br />end<br /><br />class Hello </span><span class="syntaxkeyword"><</span><span class="syntaxdefault"> MyBaseClass<br /> foo</span><span class="syntaxkeyword">(</span><span class="syntaxdefault"> </span><span class="syntaxkeyword">;</span><span class="syntaxdefault">lorem</span><span class="syntaxkeyword">,</span><span class="syntaxdefault"> </span><span class="syntaxkeyword">;</span><span class="syntaxdefault">ipsum </span><span class="syntaxkeyword">)<br /></span><span class="syntaxdefault">end<br /></span>
It was pretty much what I had tried before posting the question, but I'd forgotten to add
self.
... -
Found the solution here: http://www.vitarara.org/cms/ruby_metaprogamming_declaratively_adding_methods_to_a_class
-
@thomthom said:
I was wondering if it was possible to define your own attr like syntax?
I really think they missed an attr-like method for modules and classes that creates and inits class @@ vars.
-
-
maybe add an example in this thread (maybe original post) to have it for further searches. thanks.
-
@unknownuser said:
maybe add an example in this thread (maybe original post) to have it for further searches. thanks.
Done!
-
Need to prepend the subject with "[Code]" so Jim's indexer will 'snag' it ...
-
Doubledone!
Advertisement