Class: SSHKit::EC2InstanceConnect::TimedHash
- Inherits:
-
Object
- Object
- SSHKit::EC2InstanceConnect::TimedHash
- Defined in:
- lib/sshkit/ec2instanceconnect/timed_hash.rb
Overview
A thread-safe Hash that expires keys after a given time.
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
- #clear ⇒ Object
-
#initialize(expires_in:) ⇒ TimedHash
constructor
A new instance of TimedHash.
- #size ⇒ Object
Constructor Details
#initialize(expires_in:) ⇒ TimedHash
Returns a new instance of TimedHash.
9 10 11 12 |
# File 'lib/sshkit/ec2instanceconnect/timed_hash.rb', line 9 def initialize(expires_in:) @expires_in = expires_in @store = Concurrent::Map.new end |
Instance Method Details
#[](key) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/sshkit/ec2instanceconnect/timed_hash.rb', line 18 def [](key) now = Time.now data = @store.compute_if_present(key) do |value| # Expired → delete by returning nil. if now > value[:expires_at] nil else value # keep end end data&.fetch(:value) end |
#[]=(key, value) ⇒ Object
14 15 16 |
# File 'lib/sshkit/ec2instanceconnect/timed_hash.rb', line 14 def []=(key, value) @store[key] = { value: value, expires_at: Time.now + @expires_in } end |
#clear ⇒ Object
37 38 39 |
# File 'lib/sshkit/ec2instanceconnect/timed_hash.rb', line 37 def clear @store.clear end |
#size ⇒ Object
33 34 35 |
# File 'lib/sshkit/ec2instanceconnect/timed_hash.rb', line 33 def size @store.values.count { |value| Time.now <= value[:expires_at] } end |