Rails: how to get all key values โ€‹โ€‹from Rails.cache

I want to store a custom online / offline list with Rails.cache (memory_store).

Basically, if the request /user/heartbeat?name=John

reaches the Rails server, it just:

def update_status
  name = params.require(:name)
  Rails.cache.write(name, Time.now.utc.iso8601, expires_in: 6.seconds)
end

      

But how can I get all the data stored in Rails.cache like below?

def get_status
  # wrong codes, as Rails.cache.read doesn't have :all option.
  ary = Rails.cache.read(:all)
  # deal with array ...
end

      

I've searched Google for a while, it seems that Rails.cache doesn't provide a method to get all the data directly. Or is there a better way to store data?

I am using Rails 5.0.2

.

Thank you for your time!

+5


source to share


2 answers


You can get all keys with code:



keys = Rails.cache.instance_variable_get(:@data).keys

      

+2


source


Alternatively, you can iterate over the keys to get their values โ€‹โ€‹and display them all

keys = Rails.cache.instance_variable_get(:@data).keys
keys.each{|key| puts "key: #{key}, value: #{Rails.cache.fetch(key)}"}

      

or map them all directly as such:

key_values = Rails.cache.instance_variable_get(:@data).keys.map{|key| {key: key, value: Rails.cache.fetch(key)}}

      



Also, I would check the number of keys ahead of time to make sure I don't come up with a giant object (and if so, limit the key_value array generated by the first 1000 elements, for example). You can use:

Rails.cache.instance_variable_get(:@data).keys.count

      

or just look at the last line of the stats command:

Rails.cache.stats

      

0


source







All Articles