I'm doing a code that need to search a external API, but during development I haven't access to this API, so my current solution to run the server and navigate through the system is:
def api_call
return { fake: 'This is a fake return' } if Rails.env.development?
# api interaction code
# ...
end
This let my code dirt, so my question is: There are a pattern (or a better way) to do this?
The pattern I use is to replace api object with one that fakes all methods when in development.
class Api
def query
# perform api query
end
end
class FakeApi
def query
{ fake: 'This is a fake return' }
end
end
# config/environments/production.rb
config.api = Api.new
# config/environments/test.rb
# config/environments/development.rb
config.api = FakeApi.new
# then
def api_call
Rails.configuration.api.query # no branching here! code is clean
end
Basically, you have two classes, Api which does real work and FakeApi that returns pre-baked faked responses. You then use Rails' environment configuration to set different apis in different environments. This way, your client code (that calls #query) doesn't have to care about current environment.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With