Glenn Smith
3/29/2005 6:09:00 PM
A similar thing has just been discussed on the RubyOnRails list, and
James Britt gave a good example which I'll paste here. It's
implemented (in this case at least) using "meta programming" which is
something I'm just reading up on at the moment, because it foxed me
to!!
Here is James' example:
A simple example
# Meta-programming
# Add a public array property to an object instance
class Meta
def self.has_many( sym )
attr_tmp = "def #{sym.to_s} \n"
attr_tmp << " @#{sym.to_s} = [] unless @#{sym.to_s}\n"
attr_tmp << " @#{sym.to_s}; end"
eval ( attr_tmp )
end
end
class Foo < Meta
has_many :foo
has_many :baz
end
f = Foo.new
# See what methds the new object has ...
puts (f.methods - Object.methods ).inspect # ["foo", "baz"]
f.foo.push "X"
f.baz << "hello"
p f.foo.first # "X"
p f.baz # ["hello"]
James Britt
On Wed, 30 Mar 2005 02:57:58 +0900, Luke Renn <goseigen@comcast.net> wrote:
> What is the proper term for things like attr :<id> and belongs_to
> :<model>, etc. How do you code them? I tried googling around, but
> since I don't know what to call it, its a little tough. I looked at
> the ActiveRecord code for a few minutes and it looks like they're just
> class methods, but I don't understand how ruby interprets it i guess.
>
> Thanks.
>
> --
> Luke | PGP: 0xFBE7D8AF
> goseigen@comcast.net | 2A44 9EB2 F541 C1F2 D969 56E3 8617 5B7F FBE7 D8AF
>
>
--
All the best
Glenn
Aylesbury, UK