Last active
August 29, 2015 14:02
-
-
Save janko/f846a0a1a93b361e3471 to your computer and use it in GitHub Desktop.
Example Faraday integration with the LDAP protocol, with caching to the database.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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