Using class instance variables in ruby

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Object
  def self.metaclass; class << self; self; end; end
 
  def self.iattr_accessor *args
 
    metaclass.instance_eval do
      attr_accessor *args
      args.each do |attr|
        define_method("set_#{attr}") do |b_value|
          self.send("#{attr}=",b_value)
        end
      end
    end
 
    args.each do |attr|
      class_eval do
        define_method(attr) do
          self.class.send(attr)
        end
        define_method("#{attr}=") do |b_value|
          self.class.send("#{attr}=",b_value)
        end
      end
    end
  end
end

Now you can easily write code like this:

1
2
3
4
5
6
class Foobar
  iattr_accessor :hello
end
 
Foobar.hello = "I am a class instance atrribute"
p Foobar.hello

Leave a Reply

Your email address will not be published. Required fields are marked *