Skip to content

Instantly share code, notes, and snippets.

@smarterclayton
Created August 15, 2012 17:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smarterclayton/3361943 to your computer and use it in GitHub Desktop.
Save smarterclayton/3361943 to your computer and use it in GitHub Desktop.
Mixin for Her that adds user contextual specialization of a Her ORM object
module ConsoleModel
module Middleware
class Authorizes < Faraday::Request::BasicAuthentication
def initialize(app, auth)
super app, auth.login, auth.password
end
def call(env)
puts "call authorizes"
super
end
end
end
end
#
# Provides an "as" relation that allows authorization via the ConsoleModel::Middleware::Authorize
#
module ConsoleModel::WithAuthorization
extend ActiveSupport::Concern
included do
end
module SharedMethods
protected
def specialize_her_api(with, &block)
uses_api(with ? Her::API.specialize(with, &block) : nil)
end
end
module InstanceMethods
include SharedMethods
def initialize(single_data={})
super
self.class.relationships.each_pair do |type, relationships|
relationships.each do |relationship|
if @data.include?(relationship[:name])
if type == :authorizes
authorizes = @data.delete(relationship[:name])
end
end
end
end
@data
end
end
module ClassMethods
include SharedMethods
def authorizes(*args) # {{{
attrs = args.extract_options!
name = args.first || :as
@her_relationships ||= {}
(@her_relationships[:authorizes] ||= []) << attrs.merge(:name => name)
define_method(name) do
@authorizes
end
define_method("#{name}=") do |auth|
@authorizes = auth
uses_api nil
if auth
specialize_her_api self.class.her_api do |builder|
builder.insert 0, attrs[:with], auth
end
end
end
self.class.instance_eval do
define_method(name) do |auth|
@authorizes = auth
specialize_her_api her_api do |builder|
builder.insert 0, attrs[:with], auth
end
end
end
end # }}}
end
end
class Her::API
def self.specialize(other, &block)
builder = other.connection.builder.dup
yield builder if block_given?
api = new
api.setup :base_uri =>other.base_uri, :builder => builder
api
end
def setup(attrs={}) # {{{
@base_uri = attrs[:base_uri]
@connection = Faraday.new(:url => @base_uri, :builder => attrs[:builder]) do |connection|
yield connection.builder if block_given?
end
end # }}}
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment