Created
February 17, 2022 07:11
-
-
Save elct9620/bb924ada236470eae4cc8a9b9e826d73 to your computer and use it in GitHub Desktop.
Use Ruby's SimpleDelegator to implement middleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
require 'delegate' | |
require 'json' | |
class Middleware < SimpleDelegator | |
end | |
class CacheMiddleware < Middleware | |
def initialize(object) | |
super | |
@cache = {} | |
end | |
def call(*args, **params) | |
endpoint, = args | |
return @cache[endpoint] if @cache[endpoint] | |
super | |
end | |
end | |
class RetryMiddleware < Middleware | |
def call(*args, **params) | |
retry_count = 0 | |
begin | |
super | |
rescue StandardError | |
raise if retry_count >= 3 | |
retry_count += 1 | |
retry | |
end | |
end | |
end | |
class Client | |
def now_time | |
call('/now_time') | |
end | |
def call(*_args, **_params) | |
# Fake API Response | |
{ timestamp: Time.now.to_i }.to_json | |
end | |
end | |
client = [CacheMiddleware, RetryMiddleware].reduce(Client.new) do |client, middleware| | |
middleware.new(client) | |
end | |
puts client.now_time | |
# Cached | |
puts client.now_time |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment