Module: Dry::BlackTie

Defined in:
lib/dry/behaviour/black_tie.rb

Overview

rubocop:disable Style/MultilineBlockChain rubocop:disable Metrics/MethodLength rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/AbcSize rubocop:disable Style/MethodName

Constant Summary collapse

DELEGATE_METHOD =
lambda do |klazz, (source, target)|
  klazz.class_eval do
    define_method(source, &Dry::DEFINE_METHOD.curry[target])
  end
end
POSTPONE_EXTEND =
lambda do |target, protocol|
  TracePoint.new(:end) do |tp|
    if tp.self == protocol
      target.extend protocol
      tp.disable
    end
  end.enable
end

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.defimpl(protocol = nil, target: nil, delegate: [], map: {}) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/dry/behaviour/black_tie.rb', line 81

def defimpl(protocol = nil, target: nil, delegate: [], map: {})
  raise if target.nil? || !block_given? && delegate.empty? && map.empty?

  mds = normalize_map_delegates(delegate, map)

  Module.new do
    mds.each(&DELEGATE_METHOD.curry[singleton_class])
    singleton_class.class_eval(&Proc.new) if block_given? # block takes precedence
  end.tap do |mod|
    protocol ? mod.extend(protocol) : POSTPONE_EXTEND.(mod, protocol = self)

    mod.methods(false).tap do |meths|
      (BlackTie.protocols[protocol].keys - meths).each_with_object(meths) do |m, acc|
        BlackTie.Logger.warn("Implicit delegate #{protocol.inspect}##{m} to #{target}")
        DELEGATE_METHOD.(mod.singleton_class, [m] * 2)
        acc << m
      end
    end.each do |m|
      target = [target] unless target.is_a?(Array)
      target.each do |tgt|
        BlackTie.implementations[protocol][tgt][m] = mod.method(m).to_proc
      end
    end
  end
end

.implementationsObject



13
14
15
# File 'lib/dry/behaviour/black_tie.rb', line 13

def implementations
  @implementations ||= Hash.new { |h, k| h[k] = h.dup.clear }
end

.LoggerObject



108
109
110
111
112
113
114
115
# File 'lib/dry/behaviour/black_tie.rb', line 108

def self.Logger
  @logger ||= if Kernel.const_defined?('::Rails')
                Rails.logger
              else
                require 'logger'
                Logger.new($stdout)
              end
end

.normalize_map_delegates(delegate, map) ⇒ Object



119
120
121
122
123
124
125
126
# File 'lib/dry/behaviour/black_tie.rb', line 119

def normalize_map_delegates(delegate, map)
  [*delegate, *map].map do |e|
    case e
    when Symbol, String then [e.to_sym] * 2
    when Array then e.map(&:to_sym) if e.size == 2
    end
  end.compact
end

.protocolsObject



9
10
11
# File 'lib/dry/behaviour/black_tie.rb', line 9

def protocols
  @protocols ||= Hash.new { |h, k| h[k] = h.dup.clear }
end

Instance Method Details

#defmethod(name, *params) ⇒ Object



62
63
64
# File 'lib/dry/behaviour/black_tie.rb', line 62

def defmethod(name, *params)
  BlackTie.protocols[self][name] = params
end

#defprotocolObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/dry/behaviour/black_tie.rb', line 18

def defprotocol
  raise if BlackTie.protocols.key?(self) # DUPLICATE DEF
  raise unless block_given?

  ims = instance_methods(false)
  class_eval(&Proc.new)
  (instance_methods(false) - ims).each { |m| class_eval { module_function m } }

  singleton_class.send :define_method, :method_missing do |method, *_args|
    raise Dry::Protocol::NotImplemented.new(
      :method, inspect, method: method, self: self
    )
  end

  singleton_class.send :define_method, :implementation_for do |receiver|
    receiver.class.ancestors.lazy.map do |c|
      BlackTie.implementations[self].fetch(c, nil)
    end.reject(&:nil?).first
  end

  BlackTie.protocols[self].each do |method, *_| # FIXME: CHECK ARITY HERE
    singleton_class.send :define_method, method do |receiver = nil, *args|
      impl = implementation_for(receiver)
      raise Dry::Protocol::NotImplemented.new(
        :protocol, inspect,
        method: method, receiver: receiver, args: args, self: self
      ) unless impl
      begin
        impl[method].(*args.unshift(receiver))
      rescue => e
        raise Dry::Protocol::NotImplemented.new(
            :nested, inspect,
            cause: e,
            method: method, receiver: receiver, args: args, impl: impl, self: self
          )
      end
    end
  end

  singleton_class.send :define_method, :respond_to? do |method|
    BlackTie.protocols[self].keys.include? method
  end
end