class EightBall::Providers::RefreshPolicies::Interval

An Interval RefreshPolicy states that data is considered fresh for a certain amount of time, after which it is considered stale and should be refreshed.

Constants

SECONDS_IN_A_DAY

Public Class Methods

new(seconds = 60) click to toggle source

Creates a new instance of an Interval RefreshPolicy.

@param seconds [Integer] The number of seconds the data is considered fresh.

@example New data stays fresh for 2 minutes

EightBall::Providers::RefreshPolicies::Interval.new 120
# File lib/eight_ball/providers/refresh_policies/interval.rb, line 17
def initialize(seconds = 60)
  @interval = seconds
  @fresh_until = nil
end

Public Instance Methods

refresh() { || ... } click to toggle source

Yields if the current data is stale, in order to refresh it. Resets the interval once the data is refreshed.

@example Load new data if current data is stale

policy.refresh { load_new_data }
# File lib/eight_ball/providers/refresh_policies/interval.rb, line 27
def refresh
  return unless block_given? && stale?

  yield
  @fresh_until = DateTime.now + Rational(@interval, SECONDS_IN_A_DAY)
end

Protected Instance Methods

stale?() click to toggle source
# File lib/eight_ball/providers/refresh_policies/interval.rb, line 36
def stale?
  @fresh_until.nil? || DateTime.now > @fresh_until
end