Skip to content

Instantly share code, notes, and snippets.

@janko
Last active August 29, 2015 14:02
Show Gist options
  • Save janko/f846a0a1a93b361e3471 to your computer and use it in GitHub Desktop.
Save janko/f846a0a1a93b361e3471 to your computer and use it in GitHub Desktop.
Example Faraday integration with the LDAP protocol, with caching to the database.
require "faraday"
module Faraday
class Adapter
class NetLdap < Faraday::Adapter
def call(env)
# LDAP request, and call `save_response(env, status, body, headers)`
@app.call(env)
end
end
end
end
Faraday::Middleware.register_middleware :net_ldap => Faraday::Adapter::NetLdap
module MyMiddleware
class Cache < Faraday::Response::Middleware
def initialize(app, options = {})
super(app)
@last_updated = options.fetch(:last_updated)
@cache = options.fetch(:cache)
@expires_in = options.fetch(:expires_in)
end
def call(env)
if Time.now - @last_updated.call >= @expires_in
super
end
end
def on_complete(env)
@cache.call env[:body] # Assuming env[:body] is array of Ruby hashes
end
end
end
connection = Faraday.new("ldap://example.com", connection_options) do |b|
b.use MyMiddleware::Cache, last_updated: -> { MyModel.max(:created_at) },
expires_in: 4.hours,
cache: MyModel.method(:create)
b.adapter :net_ldap
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment