Skip to content

Instantly share code, notes, and snippets.

@serradura
Created May 2, 2022 17:10
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serradura/72c46875fddd3945a93fd49ced8fed00 to your computer and use it in GitHub Desktop.
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
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