class Resolve::Hostname::CachedValue

Attributes

expires[RW]
mutex[RW]
value[RW]

Public Class Methods

new(ttl) click to toggle source

TODO: negative cache

# File lib/resolve/hostname.rb, line 175
def initialize(ttl)
  @value = nil
  @ttl = ttl
  @expires = Time.now + ttl
  @mutex = Mutex.new
end

Public Instance Methods

get_or_refresh() { || ... } click to toggle source
# File lib/resolve/hostname.rb, line 182
def get_or_refresh
  return @value if @value && @expires >= Time.now

  @mutex.synchronize do
    return @value if @value && @expires >= Time.now

    @value = yield
    # doesn't do negative cache (updating of @expires is passed when something raised above)
    @expires = Time.now + @ttl
  end

  @value
end