We all know how evil class variables are, and they are as dangerous as the “three headed dog” at the dungeon and we shall not talk about it.
But they are necessary for many of the thingies ruby does and used extensively.But today we shall not talk about them.
We saw earlier that, although class instance variables are excellent, but not so friendly to use and they make Ruby look like C++(ahem).
Here goes a little hack, that allows you to define class level attributes based on class instance variables. Since, i often use it in rails and they have taken cattr for class level attributes.
class Object
def self.metaclass; class << self; self; end; end
def self.iattr_accessor *args
metaclass.instance_eval do
attr_accessor *args
end
args.each do |attr|
class_eval do
define_method(attr) do
self.class.send(attr)
end
end
end
end
end
What above code does is, creates those class instance variables at class scope and also creates accessor methods for it, so that it doesn’t have to suck when used from class instances(remember @foo.class.i_am_class_instance_var)
Here is a sample that, shows it in action:
class Foobar
iattr_accessor :foo
end
Foobar.foo = "Hemant"
p Foobar.foo
lol = Foobar.new
p lol.foo
Did i miss anything? comments?