Created
May 2, 2022 17:10
-
-
Save serradura/72c46875fddd3945a93fd49ced8fed00 to your computer and use it in GitHub Desktop.
Example of how to use the strategy pattern in Ruby to create a fake and a real API client
This file contains hidden or 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
require 'uri' | |
require 'json' | |
require 'net/http' | |
# https://dog.ceo/dog-api/ | |
class DogCeoAPI | |
class FakeStrategy | |
def get_random | |
{ | |
"message" => "https://images.dog.ceo/breeds/terrier-welsh/lucy.jpg", | |
"status" => "success" | |
} | |
end | |
end | |
class ClientStrategy | |
def get_random | |
uri = URI('https://dog.ceo/api/breeds/image/random') | |
response = Net::HTTP.get_response(uri) | |
JSON.parse(response.body) | |
end | |
end | |
def initialize(client:) | |
@client = client.new | |
end | |
def get_random | |
@client.get_random | |
end | |
end | |
dog_ceo = DogCeoAPI.new(client: DogCeoAPI::FakeStrategy) | |
p dog_ceo.get_random | |
dog_ceo = DogCeoAPI.new(client: DogCeoAPI::ClientStrategy) | |
p dog_ceo.get_random |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment