Module: Strict::Interfaces::Instance

Defined in:
lib/strict/interfaces/instance.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#implementationObject (readonly)

Returns the value of attribute implementation.



6
7
8
# File 'lib/strict/interfaces/instance.rb', line 6

def implementation
  @implementation
end

Instance Method Details

#initialize(implementation) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity



9
10
11
12
13
14
15
16
17
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
# File 'lib/strict/interfaces/instance.rb', line 9

def initialize(implementation)
  missing_methods = nil
  invalid_method_definitions = Hash.new do |h, k|
    h[k] = { additional_parameters: [], missing_parameters: [], non_keyword_parameters: [] }
  end

  self.class.strict_instance_methods.each do |method_name, strict_method| # rubocop:disable Metrics/BlockLength
    unless implementation.respond_to?(method_name)
      missing_methods ||= []
      missing_methods << method_name
      next
    end

    expected_parameters = Set.new(strict_method.parameters.map(&:name))
    defined_parameters = Set.new
    has_keyword_splat = false

    implementation.method(method_name).parameters.each do |kind, parameter_name|
      case kind
      when :block, :rest
        next
      when :keyrest
        has_keyword_splat = true
        next
      end

      if expected_parameters.include?(parameter_name)
        defined_parameters.add(parameter_name)
        invalid_method_definitions[method_name][:non_keyword_parameters] << parameter_name if kind != :keyreq
      else
        invalid_method_definitions[method_name][:additional_parameters] << parameter_name
      end
    end

    next if has_keyword_splat

    missing_parameters = expected_parameters - defined_parameters
    invalid_method_definitions[method_name][:missing_parameters] = missing_parameters if missing_parameters.any?
  end

  if missing_methods || !invalid_method_definitions.empty?
    raise Strict::ImplementationDoesNotConformError.new(
      interface: self.class,
      receiver: implementation,
      missing_methods: missing_methods,
      invalid_method_definitions: invalid_method_definitions
    )
  end

  @implementation = implementation
end