Permalink
Browse files

Creating singleton class for every object whenever the instance-level…

… accessor is used quite is expensive.
  • Loading branch information...
1 parent 5a51848 commit 320382ccd359397f2c83f8c0c622b296dcfb472b @thedarkone thedarkone committed Sep 24, 2010
Showing with 21 additions and 1 deletion.
  1. +21 −1 activesupport/lib/active_support/core_ext/class/attribute.rb
@@ -72,11 +72,20 @@ def self.#{name}=(val)
remove_possible_method(:#{name})
define_method(:#{name}) { val }
end
+
+ if singleton_class?
+ class_eval do
+ remove_possible_method(:#{name})
+ def #{name}
+ defined?(@#{name}) ? @#{name} : singleton_class.#{name}
+ end
+ end
+ end
val
end
def #{name}
- defined?(@#{name}) ? @#{name} : singleton_class.#{name}
+ defined?(@#{name}) ? @#{name} : self.class.#{name}
end
def #{name}?
@@ -87,4 +96,15 @@ def #{name}?
attr_writer name if instance_writer
end
end
+
+ private
+ def singleton_class?
+ # in case somebody is crazy enough to overwrite allocate
+ allocate = Class.instance_method(:allocate)
+ # object.class always points to a real (non-singleton) class
+ allocate.bind(self).call.class != self
+ rescue TypeError
+ # MRI/YARV/JRuby all disallow creating new instances of a singleton class
+ true
+ end
end

0 comments on commit 320382c

Please sign in to comment.