Skip to content

Instantly share code, notes, and snippets.

@kei-p
Last active April 11, 2016 05:53
Show Gist options
  • Save kei-p/2cac824a31987c74ac18ac2c4db34e4b to your computer and use it in GitHub Desktop.
Save kei-p/2cac824a31987c74ac18ac2c4db34e4b to your computer and use it in GitHub Desktop.
DummyResponse with Faraday
require 'bundler/setup'
Bundler.require
module Faraday
class Dummy < Faraday::Middleware
def call(env)
if Random.new.rand(0..1) == 0
@app.call(env).on_complete do |env|
env
end
else
dummy_response(env)
end
end
private
def dummy_response(env)
puts 'dummy request =>'
body = {
dummy: "aaaaaaaaaaaaaaaaaaaaaaaaa"
}.to_json
env.update(
status: 200,
body: body,
response_headers: {
'content-type' => 'application/json'
}
)
Faraday::Response.new(env)
end
end
end
module Faraday
class Logger < Faraday::Middleware
def call(env)
puts 'request =>'
@app.call(env).on_complete do |env|
env
end
end
end
end
conn = Faraday.new(url: 'https://api.ipify.org') do |builder|
builder.response :json
builder.use Faraday::Dummy
builder.use Faraday::Logger
builder.adapter Faraday.default_adapter
end
res = conn.get '', {format: 'json'}
puts res.body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment