Class: SpreeLegacyApiV2::Engine

Inherits:
Rails::Engine
  • Object
show all
Defined in:
lib/spree_legacy_api_v2/engine.rb

Class Method Summary collapse

Class Method Details

.merge_v2_dependencies_into_api!Object



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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/spree_legacy_api_v2/engine.rb', line 21

def merge_v2_dependencies_into_api!
  api_deps_class = Spree::Api::ApiDependencies
  v2_defaults = SpreeLegacyApiV2::ApiDependencies::INJECTION_POINTS_WITH_DEFAULTS

  # Collect all new V2 points that don't exist in V3
  new_points = []

  v2_defaults.each do |point, default_value|
    # Skip if already defined (V3 has priority)
    next if api_deps_class::INJECTION_POINTS.include?(point)

    new_points << point

    # Define getter
    api_deps_class.attr_reader(point)

    # Define setter with override tracking
    api_deps_class.define_method("#{point}=") do |value|
      @overrides ||= {}
      @overrides[point] = {
        value: value,
        source: find_caller_source,
        set_at: Time.current
      }
      remove_instance_variable("@#{point}_resolved") if instance_variable_defined?("@#{point}_resolved")
      instance_variable_set("@#{point}", value)
    end

    # Define _class method for resolved class access
    api_deps_class.define_method("#{point}_class") do
      return instance_variable_get("@#{point}_resolved") if instance_variable_defined?("@#{point}_resolved")

      value = send(point)
      resolved = case value
                 when String then value.constantize
                 when Proc then value.call.then { |v| v.is_a?(String) ? v.constantize : v }
                 else value
                 end
      instance_variable_set("@#{point}_resolved", resolved)
      resolved
    end

    # Set the default value on the existing Dependencies instance
    value = default_value.respond_to?(:call) ? default_value.call : default_value
    Spree::Api::Dependencies.instance_variable_set("@#{point}", value)
  end

  # Update INJECTION_POINTS constant with all new points at once
  return unless new_points.any?

  combined_points = (api_deps_class::INJECTION_POINTS.to_a + new_points).freeze
  api_deps_class.send(:remove_const, :INJECTION_POINTS)
  api_deps_class.const_set(:INJECTION_POINTS, combined_points)
end