[prev in list] [next in list] [prev in thread] [next in thread]
List: ruby-talk
Subject: Re: class methods like attr:
From: Wilson Bilkovich <wilsonb () gmail ! com>
Date: 2006-01-23 15:23:55
Message-ID: d4e4955b0601230651m612b9e88j5f36ad06016dce3 () mail ! gmail ! com
[Download RAW message or body]
Check this tutorial/game/artwork out:
http://poignantguide.net/dwemthy/
By the end, you will definitely know how to create methods that behave
like attr_accessor.
On 1/21/06, Gioele Barabucci <ml@gioelebarabucci.com> wrote:
> How can I create methods like "attr:" that can create methods and instance
> variables?
>
> I'd like to do this
>
> class B < A
> my_property :k, "K"
> def test
> p @k # should print "K"
> p @@my_properties # should print ['k']
> end
> end
>
> I tried with this (non-) solution
>
> class A
> def A.my_property(sym, val)
> self.instance_eval {
> @@my_properties ||= Array.new()
> @@my_properties << sym.to_s
> eval "@#{sym.id2name} = \"#{val}\""
> # p @k1 # << this shows "K1.B" or "K1.C" as expected
> }
> end
> end
>
> but these tests showed me that I was wrong
>
> class A
> def test
> p @@my_properties
> end
> end
>
> class B < A
> my_property :k1, "K1.B" # k1 is a string fixed to "K1"
> my_property :k2, "K2.B"
> def test
> super # should be ['k1', 'k2']
> p @k1 # should be "K1"
> end
> end
>
> class C < A
> my_property :k1, "K1.C"
> def test
> super # should be ['k1']
> p @k1 # should be "K1.C"
> end
> end
>
> A.new.test (should print nil or a warning) => ["k1", "k2", "k1"]
>
> B.new.test (should print ['k1', 'k2'] 'K1.B') => ["k1", "k2", "k1"]
> ./at.rb:28: warning: instance variable @k1 not initialized
> nil
>
> A.new.test (should print nil or a warning) => ["k1", "k2", "k1"]
>
> C.new.test (should print ['k1'] 'K1.C') => ["k1", "k2", "k1"]
> ./at.rb:36: warning: instance variable @k1 not initialized
> nil
>
> Any suggestion or idea?
>
> --
> Gioele <dev@gioelebarabucci.com>
>
>
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic