|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +# Walks the constants Grape's lib defines, private ones included, to check |
| 4 | +# what a non-main Ractor could read. Constants still to autoload are the files |
| 5 | +# Grape leaves out of eager loading, which would load Rails, and are skipped. |
| 6 | +module GrapeConstants |
| 7 | + LIB = File.expand_path('../../lib', __dir__) |
| 8 | + |
| 9 | + module_function |
| 10 | + |
| 11 | + # The names of the constants, modules aside, whose value the block answers |
| 12 | + # falsy for. |
| 13 | + def failing |
| 14 | + Grape.deprecator.silence do |
| 15 | + grape_modules.flat_map { |mod| constants_of(mod) }.filter_map do |name, value| |
| 16 | + name unless value.is_a?(Module) || yield(value) |
| 17 | + end |
| 18 | + end |
| 19 | + end |
| 20 | + |
| 21 | + def grape_modules |
| 22 | + ObjectSpace.each_object(Module).select do |mod| |
| 23 | + name = name_of(mod) |
| 24 | + name == 'Grape' || name&.start_with?('Grape::') |
| 25 | + end |
| 26 | + end |
| 27 | + |
| 28 | + def constants_of(mod) |
| 29 | + constant_names_of(mod).filter_map do |name| |
| 30 | + next unless defined_in_lib?(mod, name) |
| 31 | + |
| 32 | + ["#{name_of(mod)}::#{name}", mod.const_get(name, false)] |
| 33 | + end |
| 34 | + end |
| 35 | + |
| 36 | + # Module#constants leaves private constants out, so their names are read |
| 37 | + # from the source. |
| 38 | + def constant_names_of(mod) |
| 39 | + mod.constants(false) | private_constant_names.select { |name| mod.const_defined?(name, false) } |
| 40 | + end |
| 41 | + |
| 42 | + def private_constant_names |
| 43 | + Dir["#{LIB}/**/*.rb"] |
| 44 | + .flat_map { |file| File.read(file).scan(/private_constant\s+([^\n#]+)/).flatten } |
| 45 | + .flat_map { |names| names.scan(/:(\w+)/).flatten } |
| 46 | + .uniq.map(&:to_sym) |
| 47 | + end |
| 48 | + |
| 49 | + def defined_in_lib?(mod, name) |
| 50 | + !mod.autoload?(name) && mod.const_source_location(name)&.first&.start_with?(LIB) |
| 51 | + end |
| 52 | + |
| 53 | + def name_of(mod) |
| 54 | + Module.instance_method(:name).bind_call(mod) |
| 55 | + end |
| 56 | +end |
0 commit comments