This worked when put into the class itself but not when using "extend"? Any
idea why?

Thanks

Steve Tuckner :))

-----Original Message-----
From: Mathieu Bouchard [mailto:matju / sympatico.ca]
Sent: Monday, June 18, 2001 11:35 PM
To: ruby-talk / ruby-lang.org; Steve Tuckner
Cc: ruby-talk ML
Subject: [ruby-talk:16617] Re: Class Var question



On Tue, 19 Jun 2001, Steve Tuckner wrote:
> What I want to do is have some "meta" information about an object's
members.
> So for example if an object has two members: ht and wt, I want to
associated
> with them the names to display if I have an object display module. I would
> like to use the following code to use this capability.
> 	def Address
> 		uservar :street, { Name => "Street" }
> 		uservar :city, { Name => "City" }
[...]

make it like this:

class Address # this is the class

	class << self # this is the class of the class
		attr_accessor :uservars

		def uservar(sym,info)
			@uservars ||= {}
			@uservars[sym] = info
		end
	end

	uservar :street, { :Name => "Street" }
	uservar :city, { :Name => "City" }
	uservar :country, { :Name => "Country" }
	uservar :postal_code, { :Name => "Postal Code" }
end

From an Address object you can access those like this:

foo.class.uservars[:postal_code]
#==> {:Name=>"Postal Code"}

I suppose you want to share the ability to have uservars, among several 
classes. In theory, you could do:

class UserClass < Class
	...
end

but in practice you cannot :-( There are however ways to give the same
effect. Here is one:

module UserClass
	def uservar...
		put stuff here
	end
end

class Address
	extend UserClass # the Address class itself is now a UserClass

	put your calls to uservar here
end

so every class in which you say "extend UserClass" gets the uservar
feature.

matju