Skip to content

Instantly share code, notes, and snippets.

@AlexcastroDev
Last active June 6, 2024 10:55
Show Gist options
  • Save AlexcastroDev/1dc15bd56c685e452428c16a46a79c1e to your computer and use it in GitHub Desktop.
Save AlexcastroDev/1dc15bd56c685e452428c16a46a79c1e to your computer and use it in GitHub Desktop.
rate_limit_shopify.rb
# frozen_string_literal: true
require "bundler/inline"
gemfile(true) do
source "https://rubygems.org"
git_source(:github) { |repo| "https://github.com/#{repo}.git" }
gem "faker"
gem "ruby-limiter"
gem "minitest"
end
BING_API_LIMIT = 5
module SomethingLib
class ImagesLimiter
extend Limiter::Mixin
limit_method(:generate, rate: BING_API_LIMIT, interval: 1, balanced: true) do
puts "|SomethingLib| BingImageSearch global limit exceeded, waiting..."
end
def generate(title)
puts "Generating images for #{title}"
Faker::Lorem.paragraph
end
end
class Images
# hold the instance
@instance = ImagesLimiter.new
def self.generate
@instance.generate("naruto")
end
end
end
require "minitest/autorun"
class BugTest < Minitest::Test
def test_rate_limit_not_exceed
assert_output(/Generating images for naruto\nGenerating images for naruto\n/) do
2.times {
SomethingLib::Images.generate
}
end
end
def test_rate_limit_exceed
sleep(1)
assert_output(/Generating images for naruto\nGenerating images for naruto\nGenerating images for naruto\nGenerating images for naruto\nGenerating images for naruto\n\|SomethingLib\| BingImageSearch global limit exceeded, waiting...\n/) do
6.times { SomethingLib::Images.generate }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment