Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Acts as Java Class Variable (See related posts)

// Ruby's Class Variable is soooooooooooooooo confusing
// http://www.oreillynet.com/ruby/blog/2007/01/nubygems_dont_use_class_variab_1.html
// However, if we use

module JCV
  def self.included(the_class)
    class << the_class
      def acts_like_java_class_variable( *arg)

        the_class = self
        singleton_class = class << self; self; end
        arg.each do |var|
          singleton_class.send :define_method, "#{var}",
                               & lambda{ the_class.send "__real_#{var}"}
          singleton_class.send :define_method, "#{var}=",
                               & lambda{|c| the_class.send "__real_#{var}=",c}
          singleton_class.send :define_method, "__real_#{var}",
                               & lambda{ instance_variable_get "@#{var}"}
          singleton_class.send :define_method, "__real_#{var}=",
                               & lambda{|c| instance_variable_set "@#{var}", c}
        end
      end
    end
  end
end

class A
  include JCV
  acts_like_java_class_variable :count

  @count = 0
  def initialize
    A.count +=1
  end
end


You need to create an account or log in to post comments to this site.


Click here to browse all 4834 code snippets

Related Posts