Last active
November 30, 2018 02:50
-
-
Save ritikesh/09384fec25c4b05cfdec8674ce3a9076 to your computer and use it in GitHub Desktop.
Ruby/Rails Memoization pattern for dynamic methods created using metaprogramming
This file contains 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
# memoize db/memcache results in instance variable dynamically | |
def memoize_results(key) | |
return instance_variable_get(key) if instance_variable_defined?(key) | |
instance_variable_set key, yield | |
end | |
# usage | |
MY_CONSTANT = [:active, :inactive] | |
MY_CONSTANT.each { |key| | |
define_method("#{key}_users") do | |
memoize_results("@#{key}_users") do | |
User.send(key).all # assumes that user responds to active, inactive(via scope/filter etc..) | |
end | |
end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment