Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails: how to get all key-values from Rails.cache

I want to maintain an user online/offline list with Rails.cache(memory_store).

Basically if a request /user/heartbeat?name=John reached Rails server, it will simply:

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

But how could I get all the data stored in Rails.cache similarly as following?

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

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

I'm using Rails 5.0.2.

Thanks for your time!

like image 984
mCY Avatar asked May 04 '17 15:05

mCY


2 Answers

You can get all keys with code:

keys = Rails.cache.instance_variable_get(:@data).keys
like image 160
duyetpt Avatar answered Nov 08 '22 16:11

duyetpt


If you have redis you can use sth like Rails.cache.redis.keys

like image 19
sekmo Avatar answered Nov 08 '22 15:11

sekmo