Module: RailVerdict::RailsContext::ConstantInferencer

Defined in:
lib/rail_verdict/rails_context/constant_inferencer.rb

Class Method Summary collapse

Class Method Details

.infer(kind:, path:) ⇒ Object



6
7
8
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
# File 'lib/rail_verdict/rails_context/constant_inferencer.rb', line 6

def self.infer(kind:, path:)
  normalized = path.to_s.encode(Encoding::UTF_8, invalid: :replace, undef: :replace, replace: "?").strip
  normalized = normalized.delete_prefix("./").delete_prefix("/")
  normalized = normalized.unicode_normalize(:nfc) if normalized.respond_to?(:unicode_normalize)

  internal = case kind
             when "model"
               strip_prefix(normalized, "app/models/")
             when "controller"
               strip_prefix(normalized, "app/controllers/")
             when "job"
               strip_prefix(normalized, "app/jobs/")
             when "mailer"
               strip_prefix(normalized, "app/mailers/")
             when "helper"
               strip_prefix(normalized, "app/helpers/")
             when "service"
               strip_prefix(normalized, "app/services/")
             when "policy"
               strip_prefix(normalized, "app/policies/")
             when "component"
               strip_prefix(normalized, "app/components/")
             else
               return nil
             end
  return nil if internal.nil? || internal.empty?
  return nil unless internal.end_with?(".rb")

  bare = internal.delete_suffix(".rb")
  parts = bare.split("/").reject(&:empty?)
  return nil if parts.empty?

  parts.map { |segment| camelize(segment) }.join("::")
rescue StandardError
  nil
end