aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/memoizable.rb
diff options
context:
space:
mode:
authorJoshua Peek <josh@joshpeek.com>2008-07-14 19:50:32 -0500
committerJoshua Peek <josh@joshpeek.com>2008-07-14 19:50:32 -0500
commit8a9934a9d9fc98b56c4566ae2e3fd4d83e505d3e (patch)
treefe7ed2626140178c722f5245d37b23c311da5ce4 /activesupport/lib/active_support/memoizable.rb
parentd27dd860c7f4f9b9e5aebe7d0c6e9b6108d8717c (diff)
downloadrails-8a9934a9d9fc98b56c4566ae2e3fd4d83e505d3e.tar.gz
rails-8a9934a9d9fc98b56c4566ae2e3fd4d83e505d3e.tar.bz2
rails-8a9934a9d9fc98b56c4566ae2e3fd4d83e505d3e.zip
Added Memoizable mixin for caching simple lazy loaded attributes
Diffstat (limited to 'activesupport/lib/active_support/memoizable.rb')
-rw-r--r--activesupport/lib/active_support/memoizable.rb32
1 files changed, 32 insertions, 0 deletions
diff --git a/activesupport/lib/active_support/memoizable.rb b/activesupport/lib/active_support/memoizable.rb
new file mode 100644
index 0000000000..c78fb0a793
--- /dev/null
+++ b/activesupport/lib/active_support/memoizable.rb
@@ -0,0 +1,32 @@
+module ActiveSupport
+ module Memoizable
+ def self.included(base) #:nodoc:
+ base.extend(ClassMethods)
+ end
+
+ module ClassMethods
+ def memorize(symbol)
+ original_method = "_unmemorized_#{symbol}"
+ alias_method original_method, symbol
+ class_eval <<-EOS, __FILE__, __LINE__
+ def #{symbol}
+ if instance_variable_defined?(:@#{symbol})
+ @#{symbol}
+ else
+ @#{symbol} = #{original_method}
+ end
+ end
+ EOS
+ end
+ end
+
+ def freeze
+ methods.each do |method|
+ if m = method.to_s.match(/^_unmemorized_(.*)/)
+ send(m[1]).freeze
+ end
+ end
+ super
+ end
+ end
+end