sergio-fry/youtube-fetcher

View on GitHub
app/services/throttler.rb

Summary

Maintainability
A
0 mins
Test Coverage
A
100%
# Throttler.throttle "Update feeds", 1.minute do
#   ...
# end
class Throttler
  def initialize(period, name)
    @period = period
    @name = name
  end

  def action(&block)
    return if ever? && last_action_at > @period.ago

    execute_and_track(block)
  end

  def self.throttle(name, period, &block)
    new(period, name).action(&block)
  end

  private
  
  def execute_and_track(block)
    track!
    block.call
  end

  def track!
    cache.write key, Time.now.to_i, expires_in: @period
  end

  def ever?
    cache.exist?(key)
  end

  def last_action_at
    return unless cache.exist?(key)

    Time.at cache.read(key)
  end

  def key
    "Throttler:#{@name}"
  end

  def cache
    Rails.cache
  end
end