Skip to content

Instantly share code, notes, and snippets.

@softcraft-development
Last active December 19, 2015 18:48
Show Gist options
  • Save softcraft-development/6001156 to your computer and use it in GitHub Desktop.
Save softcraft-development/6001156 to your computer and use it in GitHub Desktop.
module InstanceCache
def self.included(receiver)
receiver.extend(ClassMethods)
end
module ClassMethods
# Override me for good times
def find_by_cache_key(cache_key)
find(cache_key)
end
def retrieve(cache_key)
value = instance_cache[cache_key]
if value.nil?
value = find_by_cache_key(cache_key)
set_cached_value(cache_key, value)
elsif value == ExplicitNil.instance
value = nil
end
value
end
def set_cached_value(cache_key, value)
value = ExplicitNil.instance if value.nil?
instance_cache[cache_key] = value
value
end
def instance_cache
@cache ||= {}
end
def preload_these(collection, &generate_cache_key)
unless block_given?
generate_cache_key = lambda{ |obj| obj.id }
end
collection.each do |obj|
set_cached_value(generate_cache_key.call(obj), obj)
end
end
def preload_all
preload_these(all)
end
def instances(members)
members.each do |name, value|
instance_name = name.to_s.upcase
const_name = "#{instance_name}_ID"
self.const_set const_name, value
self.class.send(:define_method, instance_name) do
retrieve(value)
end
end
end
end
class ExplicitNil < Object
include Singleton
def inspect
"ExplicitNil"
end
end
end
class Example < ActiveRecord::Base
include InstanceCache
instances :foo => 1, :bar => 2
end
puts Example.FOO
puts Example::BAR_ID
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment