Permalink
Browse files

refactor

  • Loading branch information...
1 parent 1a899a9 commit 915e7616b3d128dfe8c76f7e121b314d7cab5a77 @kachick committed Apr 14, 2012
Showing with 31 additions and 22 deletions.
  1. +25 −22 lib/flyweight.rb
  2. +6 −0 test/test_flyweight.rb
View
@@ -28,13 +28,7 @@ module Flyweight
module Eigen
def intern(*values)
- pool = if singleton_class.const_defined? POOL_NAME, false
- singleton_class.const_get POOL_NAME
- else
- singleton_class.const_set POOL_NAME, {}
- end
-
- if pool.has_key? values
+ if (pool = _pool).has_key? values
pool[values]
else
pool[values] = new(*values)
@@ -46,36 +40,45 @@ def intern(*values)
private
def inherited(klass)
- klass.singleton_class.const_set POOL_NAME, {}
+ Flyweight.define_pool! klass
+ end
+
+ def _pool
+ if singleton_class.const_defined? POOL_NAME, false
+ singleton_class.const_get POOL_NAME
+ else
+ Flyweight.define_pool! self
+ end
end
end
class << self
+ def define_pool!(mod)
+ mod.singleton_class.const_set POOL_NAME, {}
+ end
+
private
def included(mod)
- mod.module_eval do
- extend Eigen
- singleton_class.const_set POOL_NAME, {}
- end
+ mod.extend Eigen
+ define_pool! mod
end
end
def eql?(other)
- self.class == other.class && (
- sources_for = ->obj{
- obj.instance_variables.map{|var|obj.instance_variable_get var}
- }
-
- sources_for[self].__send__ __callee__, sources_for[other]
- )
+ self.class == other.class &&
+ _comparable.__send__(__callee__, other._comparable)
end
alias_method :==, :eql?
def hash
- instance_variables.inject(instance_variables.hash){|sum, var|
- instance_variable_get(var).hash ^ sum
- }
+ _comparable.inject(0){|sum, val|val.hash ^ sum}
+ end
+
+ protected
+
+ def _comparable
+ instance_variables.map{|var|instance_variable_get var}
end
end
View
@@ -44,4 +44,10 @@ def test_normaly
assert_nil hash[e]
end
+ def test_class_clone
+ klass1, klass2 = Material.clone, Material.clone
+ assert_same false, klass1.equal?(klass2)
+ assert_same false, klass1.new(:metal, 2000).equal?(klass2.new(:metal, 2000))
+ assert_same false, klass1.intern(:metal, 2000).equal?(klass2.intern(:metal, 2000))
+ end
end

0 comments on commit 915e761

Please sign in to comment.