Skip to content

Instantly share code, notes, and snippets.

@ritikesh
Last active November 30, 2018 02:50
Show Gist options
  • Save ritikesh/09384fec25c4b05cfdec8674ce3a9076 to your computer and use it in GitHub Desktop.
Save ritikesh/09384fec25c4b05cfdec8674ce3a9076 to your computer and use it in GitHub Desktop.
Ruby/Rails Memoization pattern for dynamic methods created using metaprogramming
# 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