Skip to content

Instantly share code, notes, and snippets.

@kgrz
Created November 10, 2012 17:54
Show Gist options
  • Select an option

  • Save kgrz/4051902 to your computer and use it in GitHub Desktop.

Select an option

Save kgrz/4051902 to your computer and use it in GitHub Desktop.
Using Faraday and making CouchDB return JSON. Simple middleware
# this simple plumbing makes sure that the return data is in the form of a hash.
require 'faraday'
class Main
attr_reader :conn
def initialize
@conn = Faraday.new "http://127.0.0.1:5984/somedb" do |faraday|
faraday.adapter :em_http
faraday.builder.insert(0, JSONMiddleware)
end
end
def db_stats
conn.get.body
end
end
class JSONMiddleware
def initialize(app)
@app = app
end
def call(env)
# request non-sense goes here
@app.call(env).on_complete do |env|
env[:body] = env[:body].strip.empty? JSON.parse "{}" : JSON.parse env[:body]
env[:response_headers]["Content-Type"] = 'application/json'
env[:response_headers]["Content-Length"] = env[:body].length.to_s
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment