module FmRest
module Spyke
module Model
module Connection
extend ActiveSupport::Concern
included do
class_attribute :faraday_block, instance_accessor: false, instance_predicate: false
class << self; private :faraday_block, :faraday_block=; end
self.callback_methods = { create: :post, update: :patch }.freeze
end
class_methods do
def fmrest_config
if fmrest_config_overlay
return FmRest.default_connection_settings.merge(fmrest_config_overlay, skip_validation: true)
end
FmRest.default_connection_settings
end
def fmrest_config=(settings)
settings = ConnectionSettings.new(settings, skip_validation: true)
singleton_class.redefine_method(:fmrest_config) do
overlay = fmrest_config_overlay
return settings.merge(overlay, skip_validation: true) if overlay
settings
end
end
def fmrest_config_overlay=(settings)
Thread.current[fmrest_config_overlay_key] = settings
end
def fmrest_config_overlay
Thread.current[fmrest_config_overlay_key] || begin
superclass.fmrest_config_overlay
rescue NoMethodError
nil
end
end
def clear_fmrest_config_overlay
Thread.current[fmrest_config_overlay_key] = nil
end
def with_overlay(settings, &block)
Fiber.new do
begin
self.fmrest_config_overlay = settings
yield
ensure
self.clear_fmrest_config_overlay
end
end.resume
end
def connection
super || fmrest_connection
end
def faraday(&block)
self.faraday_block = block
end
private
def fmrest_connection
memoize = false
unless fmrest_config_overlay
return @fmrest_connection if @fmrest_connection
memoize = true
end
config = ConnectionSettings.wrap(fmrest_config)
connection =
FmRest::V1.build_connection(config) do |conn|
faraday_block.call(conn) if faraday_block
conn.use FmRest::Spyke::SpykeFormatter, self
conn.use FmRest::V1::TypeCoercer, config
conn.response :json, parser_options: { symbolize_names: true }
end
@fmrest_connection = connection if memoize
connection
end
def fmrest_config_overlay_key
:"#{object_id}.fmrest_config_overlay"
end
end
def fmrest_config
self.class.fmrest_config
end
end
end
end
end