class Class # :nodoc: def cattr_reader(*syms) syms.flatten.each do |sym| class_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym} @@#{sym} end def #{sym} @@#{sym} end EOS end end def cattr_writer(*syms) syms.flatten.each do |sym| class_eval(<<-EOS, __FILE__, __LINE__) unless defined? @@#{sym} @@#{sym} = nil end def self.#{sym}=(obj) @@#{sym} = obj end def #{sym}=(obj) @@#{sym} = obj end EOS end end def cattr_accessor(*syms) cattr_reader(*syms) cattr_writer(*syms) end def shared_reader(*syms) syms.each do |sym| class_eval <<-EOS def self.#{sym} read_shared_attribute(:#{sym}) end def #{sym} self.class.#{sym} end EOS end end def shared_writer(*syms) syms.each do |sym| class_eval <<-EOS def self.#{sym}=(obj) write_shared_attribute(:#{sym}, obj) end def #{sym}=(obj) self.class.#{sym} = obj end EOS end end def shared_accessor(*syms) shared_reader(*syms) shared_writer(*syms) end def shared_attributes @shared_attributes ||= {} end def write_shared_attribute(key, value) shared_attributes[key] = value end def read_shared_attribute(key) shared_attributes[key] end def reset_shared_attributes shared_attributes.clear end private def inherited_with_shared_attributes(child) inherited_without_shared_attributes(child) if respond_to?(:inherited_without_shared_attributes) new_shared_attributes = shared_attributes.inject({}) do |memo, (key, value)| memo.update(key => (value.dup rescue value)) end child.instance_variable_set('@shared_attributes', new_shared_attributes) end alias inherited_without_shared_attributes inherited alias inherited inherited_with_shared_attributes end