module Representable::Cache::InstanceMethods

Public Instance Methods

representable_cache_key() click to toggle source
# File lib/representable/cache.rb, line 116
def representable_cache_key
  self.representable_cache_options[:cache_key] ||= Representable::Cache.default_cache_key
  self.representable_cache_options[:cache_version] ||= "v1"
  self.representable_cache_options[:cache_name] ||= self.class.name

  keys = [
    self.representable_cache_options[:cache_name],
    self.representable_cache_options[:cache_version]
  ]
  raise "cache_key or default_cache_key is required" if self.representable_cache_options[:cache_key].nil?
  if self.representable_cache_options[:cache_key].kind_of? Array
    keys += self.representable_cache_options[:cache_key].map do |k|
      self.send(k).to_s.gsub(/\s+/,'')
    end
  else
    keys << self.send(self.representable_cache_options[:cache_key]).to_s.gsub(/\s+/,'')
  end
  keys.compact.join("-")
end
representable_cache_options() click to toggle source
# File lib/representable/cache.rb, line 112
def representable_cache_options
  @representable_cache_options || self.class.representable_cache_options
end
to_hash(options={}, binding_builder=Representable::Hash::PropertyBinding) click to toggle source
Calls superclass method
# File lib/representable/cache.rb, line 94
def to_hash(options={}, binding_builder=Representable::Hash::PropertyBinding)
  return super(options, binding_builder) if !Representable::Cache.enable

  key = self.representable_cache_key

  if hash = Representable::Cache.cache.get(key)
    Representable::Cache.logger.debug "[Representable::Cache] cache hit: #{key}"
    return hash
  end

  time = Benchmark.realtime do
    hash = super(options, binding_builder)
  end
  Representable::Cache.cache.set(key, hash)
  Representable::Cache.logger.debug "[Representable::Cache] write cache: #{key} cost: #{time.to_f}"
  hash
end