Created
February 25, 2015 18:23
-
-
Save remi/4e26d07d36fe0f0d9533 to your computer and use it in GitHub Desktop.
Define memoized methods with style
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
module Memoizable | |
# This would be `extend ActiveSupport::Concern` in Rails | |
def self.included(base) | |
base.extend ClassMethods | |
end | |
module ClassMethods | |
def define_memoized(method) | |
define_method method do |*args| | |
# Prevent being called with arguments | |
raise ArgumentError, "`#{self.class.name}##{method}` is a memoized method and therefore cannot be called with arguments (arguments were #{args})" if args.any? | |
# Memoize | |
instance_variable_name = :"@#{method}" | |
return instance_variable_get(instance_variable_name) if instance_variable_defined?(instance_variable_name) | |
instance_variable_set(instance_variable_name, yield) | |
end | |
end | |
end | |
end | |
class Bar | |
include Memoizable | |
define_memoized :foo do | |
puts 'Calling “Bar#foo” logic!' | |
'yes' | |
end | |
end | |
bar = Bar.new | |
5.times { puts bar.foo } | |
# => Calling “Bar#foo” logic! | |
# => yes | |
# => yes | |
# => yes | |
# => yes | |
# => yes |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment