Module: Representable::Cache::InstanceMethods

Defined in:
lib/representable/cache.rb

Instance Method Summary collapse

Instance Method Details

#representable_cache_keyObject



116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
# 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_optionsObject



112
113
114
# 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) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# 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