class Reacto::Cache::File

Attributes

data[R]
location[R]
ttl[R]

Public Class Methods

new(location: nil, ttl: 60) click to toggle source
# File lib/reacto/cache/file.rb, line 10
def initialize(location: nil, ttl: 60)
  @location = location
  @ttl = ttl

  if @location.nil?
    fail(
      ArgumentError, 'File location is mandatory while using file cache!'
    )
  end
end

Public Instance Methods

closed?() click to toggle source
# File lib/reacto/cache/file.rb, line 43
def closed?
  return false unless ready?
  deserialize

  data.closed?
end
each() { |value| ... } click to toggle source
# File lib/reacto/cache/file.rb, line 27
def each
  return unless ready?
  deserialize

  data.each do |value|
    yield value
  end
end
error() click to toggle source
# File lib/reacto/cache/file.rb, line 50
def error
  return false unless ready?
  deserialize

  data.error
end
error?() click to toggle source
# File lib/reacto/cache/file.rb, line 36
def error?
  return false unless ready?
  deserialize

  data.error?
end
on_close() click to toggle source
# File lib/reacto/cache/file.rb, line 70
def on_close
  init_data

  data.on_close
  serialize
end
on_error(error) click to toggle source
# File lib/reacto/cache/file.rb, line 63
def on_error(error)
  init_data

  data.on_error(error)
  serialize
end
on_value(value) click to toggle source
# File lib/reacto/cache/file.rb, line 57
def on_value(value)
  init_data

  data.on_value(value)
end
ready?() click to toggle source
# File lib/reacto/cache/file.rb, line 21
def ready?
  return data.ready? unless data.nil?

  fresh?
end

Private Instance Methods

deserialize() click to toggle source
# File lib/reacto/cache/file.rb, line 87
def deserialize
  return unless fresh?

  @data ||= YAML::load(::File.read(location))
end
fresh?() click to toggle source
# File lib/reacto/cache/file.rb, line 79
def fresh?
  ::File.file?(location) && (Time.now - ::File.mtime(location)) <= ttl
end
init_data() click to toggle source
# File lib/reacto/cache/file.rb, line 83
def init_data
  @data ||= Memory.new
end
serialize() click to toggle source
# File lib/reacto/cache/file.rb, line 93
def serialize
  return if data.nil?

  ::File.open(location, 'w') do |f|
    f.write(YAML::dump(data))
  end
end