diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index b49be21..84b8540 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -59,6 +59,9 @@ jobs:
- name: Exercise opt-in Rails import checks
run: bundle exec ruby scripts/check_rails_imports.rb
+ - name: Exercise opt-in Rails association checks
+ run: bundle exec ruby scripts/check_rails_associations.rb
+
- name: Exercise read-only source exclusions
run: bundle exec ruby scripts/check_source_exclusions.rb
@@ -171,6 +174,7 @@ jobs:
ruby scripts/check_namespace_receivers.rb
ruby scripts/check_static_paths.rb
ruby scripts/check_rails_imports.rb
+ ruby scripts/check_rails_associations.rb
ruby scripts/check_source_exclusions.rb
ruby scripts/check_analysis_diagnostics.rb
ruby scripts/check_baselines.rb
diff --git a/API.md b/API.md
index bc33ec6..204171f 100644
--- a/API.md
+++ b/API.md
@@ -302,6 +302,18 @@ and unknown operands remain unresolved. No Rails boot or automatic autoload-root
The option is immutable, validated and part of graph-cache identity; it composes with either
dependency-analysis mode. Cross-file method replacement and dynamic Rails/glob values are not modeled.
+### Explicit Rails associations (unreleased)
+
+`CheckOptions.new(rails_associations: true)` independently enables dependencies from supported
+Rails model calls such as `belongs_to :store, class_name: '::Storage::Store'`. It can be combined
+with either analysis mode and with `rails_imports`; neither previously shipped option enables it.
+A unique known class declaration contributes a `:rails_association` edge with call-site and
+definition lines. It shares an edge with any import or constant reference to the same file.
+
+Use `--rails-associations` or `--no-rails-associations` in the CLI. Enabled scopes have separate
+baseline identities and report candidate, unresolved and ambiguous counts; disabled output and
+fingerprints stay unchanged. See [supported syntax and limitations](GUIDE.md#rails-associations).
+
For autoloaded projects, opt into known project constant references alongside imports:
~~~ruby
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 132155f..8159a7a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,9 @@
## 1.1.1 (unreleased)
+- Add opt-in static Rails association dependencies for explicit literal `class_name` on supported
+ model-body macros, with evidence, isolated baselines and CLI uncertainty counts. No Rails boot,
+ automatic inflection, or change to existing default graphs.
- Lazily reuse immutable node/internal/external-edge views within each cached graph analysis
across file and layer checks. Invalidation, per-rule filtering, callbacks and logging stay intact;
views trade additional retained memory for less repeated projection work.
diff --git a/GUIDE.md b/GUIDE.md
index 770901e..e6cad13 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -484,6 +484,45 @@ the helper explicitly. Rails itself documents
[`require_dependency` as obsolete for modern autoloading](https://api.rubyonrails.org/classes/ActiveSupport/Dependencies/RequireDependency.html).
This compatibility option models existing legacy/engine code, not complete Rails runtime behavior.
+
+
+### Explicit Rails association class names (unreleased, opt-in)
+
+An association may name a model in a string, with no import or ordinary constant reference:
+
+~~~ruby
+class Order < ApplicationRecord
+ belongs_to :store, class_name: '::Storage::Store'
+end
+~~~
+
+Use `ArchUnit::CheckOptions.new(rails_associations: true)` or
+`bundle exec archunit check --rails-associations`. The option is separate from both
+`rails_imports` and `dependency_analysis`. It uses the same included-source declaration index
+as expanded mode, so it adds cold analysis work even if ordinary constant reads remain off.
+
+The supported sites are bare or `self.` calls directly in a named class body whose written
+superclass is `ApplicationRecord` or `ActiveRecord::Base` (optionally root-qualified).
+Supported macros are `belongs_to`, `has_one`, `has_many` and `has_and_belongs_to_many`.
+Use a symbol association name and a literal quoted string or symbol as `class_name:`, with
+an optional literal lambda scope. Names use ASCII constant path segments. A string hash key such
+as `"class_name" => ...` is not a Rails symbol option. Dynamic values, keyword splats, duplicate
+keys, polymorphic targets,
+`as:`, `through:`, and names that would need inflection are unresolved. Indirect calls, custom
+macros, concerns, alternate receivers, and custom base-class chains are outside the scanned sites.
+
+With a leading `::`, lookup starts at root. Otherwise, names are tried under the model's full
+name, then enclosing namespaces, then root (with Rails' root-first exception when the supplied
+name equals the model's basename). This is a bounded approximation of [Active Record lookup](https://github.com/rails/rails/blob/v8.1.0/activerecord/lib/active_record/inheritance.rb#L242-L269):
+the first known candidate must have a class declaration in one included file. Ambiguous and
+non-class candidates are not guessed past. No Rails boot, class ancestry checks, autoload mapping,
+runtime aliases, overridden macro behavior, or custom inflection are evaluated.
+
+The CLI reports `rails_association_sites`, `unresolved_rails_associations`, and
+`ambiguous_rails_associations` in enabled analysis scopes. They count only the supported call
+sites encountered and do not measure semantic coverage. An import and an association can share a
+file edge and retain separate evidence. Legacy checks and baselines are unchanged when disabled.
+
### Constant References (Opt-in)
For autoloaded applications, enable dependencies from known project constants alongside imports:
@@ -706,7 +745,7 @@ Overlapping observed membership raises UserError instead of choosing a layer sil
patterns can be overridden with `PresetOptions.folders` (String or Array of source globs per layer).
Unknown/duplicate keys and empty patterns are errors. For arbitrary policies use `project_layers`.
The Rails preset is opinionated and expects a services layer; it is not full Rails/DDD verification
-and does not automatically enable `rails_imports` or constant analysis.
+and does not automatically enable `rails_imports`, constant analysis, or Rails association analysis.
For a Zeitwerk app, pass expanded analysis at check time:
~~~ruby
diff --git a/benchmark/study/README.md b/benchmark/study/README.md
index 4c8bee4..85a9160 100644
--- a/benchmark/study/README.md
+++ b/benchmark/study/README.md
@@ -90,6 +90,27 @@ medians are 150,124 → 148,852 KiB. Even graph-only RSS varies 118,360 → 128,
identical retained Ruby heap; do not attribute every high-water change to the indexes. Windows RSS
remains unavailable/null. There is no memory-reduction claim.
+## Explicit Rails association opt-in cost (#102)
+
+Run `bundle exec ruby benchmark/study/rails_association_cost.rb pkg/association-cost.json` from the
+library root. The study reuses the synthetic fixture generator and measurement helpers, replacing
+the API files with models containing explicit `class_name:` strings. It alternates five pairs
+of imports-only checks with the feature disabled/enabled across the same 2,000 files. It verifies
+zero cross-file edges off and exactly 1,000 expected, evidenced association edges on, and checks
+snapshot reuse in both modes. No target source, dependencies, or Rails boot are executed.
+
+[Raw Windows samples](rails-association-windows.json), Ruby 4.0.6, five-trial medians:
+
+| Opt-in | Cold graph | Cold allocated objects | Warm graph lookup |
+| --- | ---: | ---: | ---: |
+| Off | 1.614 s | 629,466 | 3.42 ms |
+| On | 1.860 s | 926,503 | 2.64 ms |
+
+In this fixture the opt-in adds about 0.25 s cold and 0.50 MiB of post-GC Ruby heap growth; the
+two graphs have different dependency coverage. Warm samples are small lookup timings, not evidence
+that enabling the option is faster. These local samples are not performance guarantees, and
+there is no machine-speed gate. Windows peak RSS is unavailable.
+
## Shared-policy study
`run.rb` generates Rails-like and four-engine layouts with 200 Ruby files by default. Density
diff --git a/benchmark/study/rails-association-windows.json b/benchmark/study/rails-association-windows.json
new file mode 100644
index 0000000..8beb2ad
--- /dev/null
+++ b/benchmark/study/rails-association-windows.json
@@ -0,0 +1,210 @@
+{
+ "runtime": {
+ "ruby": "4.0.6",
+ "platform": "x64-mingw-ucrt"
+ },
+ "pairs": 1000,
+ "trials": 5,
+ "samples": [
+ [
+ {
+ "enabled": false,
+ "cold": {
+ "seconds": 1.9492177999927662,
+ "allocated_objects": 629898
+ },
+ "warm": {
+ "seconds": 0.0034218000364489853,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 3807800,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4459205,
+ "peak_rss_kb": null
+ }
+ },
+ {
+ "enabled": true,
+ "cold": {
+ "seconds": 2.0290882000117563,
+ "allocated_objects": 926704
+ },
+ "warm": {
+ "seconds": 0.004275399958714843,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 4457189,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4984061,
+ "peak_rss_kb": null
+ }
+ }
+ ],
+ [
+ {
+ "enabled": true,
+ "cold": {
+ "seconds": 1.5120650000171736,
+ "allocated_objects": 926502
+ },
+ "warm": {
+ "seconds": 0.002165399957448244,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 4993781,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4986117,
+ "peak_rss_kb": null
+ }
+ },
+ {
+ "enabled": false,
+ "cold": {
+ "seconds": 1.6137248000013642,
+ "allocated_objects": 629464
+ },
+ "warm": {
+ "seconds": 0.0024252000148408115,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 4994581,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4465573,
+ "peak_rss_kb": null
+ }
+ }
+ ],
+ [
+ {
+ "enabled": false,
+ "cold": {
+ "seconds": 1.5577825999935158,
+ "allocated_objects": 629464
+ },
+ "warm": {
+ "seconds": 0.0022588999709114432,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 4463621,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4466413,
+ "peak_rss_kb": null
+ }
+ },
+ {
+ "enabled": true,
+ "cold": {
+ "seconds": 1.8740935000241734,
+ "allocated_objects": 926503
+ },
+ "warm": {
+ "seconds": 0.002644499996677041,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 4464421,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4987597,
+ "peak_rss_kb": null
+ }
+ }
+ ],
+ [
+ {
+ "enabled": true,
+ "cold": {
+ "seconds": 1.8599448000313714,
+ "allocated_objects": 926503
+ },
+ "warm": {
+ "seconds": 0.004911200026981533,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 4997061,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4988437,
+ "peak_rss_kb": null
+ }
+ },
+ {
+ "enabled": false,
+ "cold": {
+ "seconds": 1.6385640999651514,
+ "allocated_objects": 629466
+ },
+ "warm": {
+ "seconds": 0.004657200013753027,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 4997861,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4468853,
+ "peak_rss_kb": null
+ }
+ }
+ ],
+ [
+ {
+ "enabled": false,
+ "cold": {
+ "seconds": 1.3632072999607772,
+ "allocated_objects": 629466
+ },
+ "warm": {
+ "seconds": 0.00357220001751557,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 4466901,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4469693,
+ "peak_rss_kb": null
+ }
+ },
+ {
+ "enabled": true,
+ "cold": {
+ "seconds": 1.2875181999988854,
+ "allocated_objects": 926504
+ },
+ "warm": {
+ "seconds": 0.0021222999785095453,
+ "allocated_objects": 237
+ },
+ "before": {
+ "ruby_heap_bytes": 4467701,
+ "peak_rss_kb": null
+ },
+ "retained": {
+ "ruby_heap_bytes": 4990877,
+ "peak_rss_kb": null
+ }
+ }
+ ]
+ ]
+}
\ No newline at end of file
diff --git a/benchmark/study/rails_association_cost.rb b/benchmark/study/rails_association_cost.rb
new file mode 100644
index 0000000..ee4d665
--- /dev/null
+++ b/benchmark/study/rails_association_cost.rb
@@ -0,0 +1,80 @@
+# frozen_string_literal: true
+
+require 'archunit'
+require 'tmpdir'
+require_relative 'fixture'
+require_relative 'rule_samples'
+
+module PerformanceStudy
+ # Paired trials over an identical, source-only Rails-shaped fixture, with an edge oracle.
+ module RailsAssociationCost
+ def self.run(pairs:, trials:)
+ Dir.mktmpdir('archunit-association-cost') do |root|
+ fixture = Fixture.new(root:, pairs:, density: 1, shape: 'rails')
+ prepare(fixture)
+ Array.new(trials) do |index|
+ modes = index.even? ? [false, true] : [true, false]
+ modes.map { |enabled| sample(fixture, enabled) }
+ end
+ ensure
+ ArchUnit.clear_graph_cache
+ end
+ end
+
+ def self.prepare(fixture)
+ fixture.prepare
+ fixture.pairs.times do |index|
+ source = File.join(fixture.root, fixture.api(index))
+ File.write(source, <<~RUBY)
+ class Request#{index} < ApplicationRecord
+ belongs_to :store, class_name: '::Db::Store#{index}'
+ end
+ raise 'do not execute target source'
+ RUBY
+ end
+ end
+
+ def self.sample(fixture, enabled)
+ ArchUnit.clear_graph_cache
+ before = RuleSamples.heap
+ options = ArchUnit::CheckOptions.new(rails_associations: enabled)
+ cold, graph = RuleSamples.measure { extract(fixture, options) }
+ retained = RuleSamples.heap
+ warm, cached = RuleSamples.measure { extract(fixture, options) }
+ raise 'expected snapshot reuse' unless graph.equal?(cached)
+
+ verify(fixture, graph, enabled)
+ { enabled:, cold:, warm:, before:, retained: }
+ end
+
+ def self.extract(fixture, options)
+ ArchUnit::Extraction.extract_graph(fixture.root, options:)
+ end
+
+ def self.verify(fixture, graph, enabled)
+ actual = graph.reject { |edge| edge.source == edge.target }
+ expected = enabled ? fixture.oracle.sort : []
+ pairs = actual.map { |edge| [edge.source, edge.target] }.sort
+ raise 'unexpected association graph' unless pairs == expected
+ return if actual.all? { |edge| edge.import_kinds == [:rails_association] }
+
+ raise 'invalid association evidence kind'
+ end
+ private_class_method :prepare, :sample, :extract, :verify
+ end
+end
+
+if $PROGRAM_NAME == __FILE__
+ pairs = 1000
+ trials = 5
+ runs = PerformanceStudy::RailsAssociationCost.run(pairs:, trials:)
+ runtime = { ruby: RUBY_VERSION, platform: RUBY_PLATFORM }
+ report = { runtime:, pairs:, trials:, samples: runs }
+ output = ARGV.first
+ if output
+ File.write(output, JSON.pretty_generate(report))
+ puts "Validated #{trials} pairs with #{pairs * 2} source files each; evidence: #{output}"
+ else
+ puts JSON.pretty_generate(report)
+ end
+end
diff --git a/lib/archunit/cli/baseline_context.rb b/lib/archunit/cli/baseline_context.rb
index 91242d4..4bd8d35 100644
--- a/lib/archunit/cli/baseline_context.rb
+++ b/lib/archunit/cli/baseline_context.rb
@@ -17,12 +17,14 @@ def self.for(name, analysis, project_root)
end
def self.settings(scope, root)
- {
+ context = {
'root' => relative(scope[:project_root], root), 'kind' => scope[:kind],
'dependency_analysis' => scope[:dependency_analysis],
'rails_imports' => scope[:rails_imports], 'load_paths' => load_paths(scope),
'source_exclusions' => scope[:effective_source_exclusions]
}
+ context['rails_associations'] = true if scope[:rails_associations]
+ context
end
def self.relative(path, root)
diff --git a/lib/archunit/cli/options.rb b/lib/archunit/cli/options.rb
index 3bd9a8d..46b349f 100644
--- a/lib/archunit/cli/options.rb
+++ b/lib/archunit/cli/options.rb
@@ -12,7 +12,7 @@ class Options
include BaselineOptions
attr_reader :command, :project_root, :config_path, :format, :dependency_analysis, :parser,
- :rails_imports, :load_paths, :source_exclusions
+ :rails_imports, :rails_associations, :load_paths, :source_exclusions
def initialize(arguments, cwd:)
@arguments = arguments.dup
@@ -21,7 +21,7 @@ def initialize(arguments, cwd:)
@project_root = File.expand_path(cwd)
@format = json_requested? ? 'json' : 'text'
@dependency_analysis = 'imports'
- @rails_imports = false
+ @rails_imports = @rails_associations = false
@load_paths = []
@source_exclusions = []
@parser = build_parser
@@ -111,6 +111,9 @@ def analysis_options(options)
options.on('--[no-]rails-imports', 'Opt into static require_dependency imports') do |value|
@rails_imports = value
end
+ options.on('--[no-]rails-associations', 'Analyze Rails class_name options') do |value|
+ @rails_associations = value
+ end
end
end
end
diff --git a/lib/archunit/cli/report.rb b/lib/archunit/cli/report.rb
index cfafbd5..b31fe78 100644
--- a/lib/archunit/cli/report.rb
+++ b/lib/archunit/cli/report.rb
@@ -31,6 +31,7 @@ def initialize(options)
source_exclusions: options.source_exclusions,
status: 'error', rules: [], analysis: AnalysisReport.new.to_h
}
+ @payload[:rails_associations] = true if options.rails_associations
end
def add_rule(rule, violations: nil, analysis: nil)
@@ -101,6 +102,7 @@ def write_header(out)
def write_notice(out)
out.puts('Rails require_dependency imports: enabled') if payload[:rails_imports]
+ out.puts('Rails explicit association class names: enabled') if payload[:rails_associations]
case payload[:status]
when 'configured'
out.puts('Rules are configured, not evaluated.')
diff --git a/lib/archunit/cli/runner.rb b/lib/archunit/cli/runner.rb
index 3b9b6c0..f64d824 100644
--- a/lib/archunit/cli/runner.rb
+++ b/lib/archunit/cli/runner.rb
@@ -80,7 +80,8 @@ def check(rules)
Extraction.clear_graph_cache
options = Common::FluentApi::CheckOptions.new(
dependency_analysis: @options.dependency_analysis.to_sym,
- rails_imports: @options.rails_imports, load_paths: @options.load_paths,
+ rails_imports: @options.rails_imports, rails_associations: @options.rails_associations,
+ load_paths: @options.load_paths,
source_exclusions: @options.source_exclusions
)
check_rules(rules, options)
diff --git a/lib/archunit/common/extraction/import_kind.rb b/lib/archunit/common/extraction/import_kind.rb
index 85bf9d6..37dba3a 100644
--- a/lib/archunit/common/extraction/import_kind.rb
+++ b/lib/archunit/common/extraction/import_kind.rb
@@ -11,9 +11,10 @@ module ImportKind
LOAD = :load
REQUIRE_DEPENDENCY = :require_dependency
CONSTANT_REFERENCE = :constant_reference
+ RAILS_ASSOCIATION = :rails_association
ALL = [REQUIRE, REQUIRE_RELATIVE, AUTOLOAD, LOAD,
- REQUIRE_DEPENDENCY, CONSTANT_REFERENCE].freeze
+ REQUIRE_DEPENDENCY, CONSTANT_REFERENCE, RAILS_ASSOCIATION].freeze
def self.valid?(value)
ALL.include?(value)
diff --git a/lib/archunit/common/fluentapi/check_options.rb b/lib/archunit/common/fluentapi/check_options.rb
index 47ddbd9..4f27558 100644
--- a/lib/archunit/common/fluentapi/check_options.rb
+++ b/lib/archunit/common/fluentapi/check_options.rb
@@ -9,7 +9,7 @@ module FluentApi
# Immutable options shared by every terminal rule check.
CheckOptions = Data.define(
:allow_empty_tests, :logging, :clear_cache, :load_paths, :dependency_analysis,
- :rails_imports, :source_exclusions
+ :rails_imports, :source_exclusions, :rails_associations
) do
# Normalizes nil or an existing options value for terminal execution.
# @param value [CheckOptions, nil]
@@ -27,15 +27,17 @@ def self.resolve(value)
# @param load_paths [Array] additional project-contained source roots
# @param dependency_analysis [Symbol] :imports or opt-in :imports_and_constants
# @param rails_imports [Boolean] opt into static Rails require_dependency syntax
+ # @param rails_associations [Boolean] opt into explicit Rails association class names
# @param source_exclusions [Array] additional project-relative source globs
def initialize( # rubocop:disable Metrics/ParameterLists
allow_empty_tests: false, logging: nil, clear_cache: false, load_paths: [],
- dependency_analysis: :imports, rails_imports: false, source_exclusions: []
+ dependency_analysis: :imports, rails_imports: false, source_exclusions: [],
+ rails_associations: false
)
validate_boolean(allow_empty_tests, :allow_empty_tests)
validate_logging(logging)
validate_boolean(clear_cache, :clear_cache)
- validate_boolean(rails_imports, :rails_imports)
+ validate_rails_options(rails_imports, rails_associations)
load_paths = immutable_load_paths(load_paths)
source_exclusions = Common::Extraction::SourceExclusions.normalize(source_exclusions)
unless %i[imports imports_and_constants].include?(dependency_analysis)
@@ -63,8 +65,17 @@ def rails_imports?
rails_imports
end
+ def rails_associations?
+ rails_associations
+ end
+
private
+ def validate_rails_options(imports, associations)
+ validate_boolean(imports, :rails_imports)
+ validate_boolean(associations, :rails_associations)
+ end
+
def validate_boolean(value, attribute)
return if [true, false].include?(value)
diff --git a/lib/archunit/extraction/analysis_snapshot.rb b/lib/archunit/extraction/analysis_snapshot.rb
index 3614d61..41a65af 100644
--- a/lib/archunit/extraction/analysis_snapshot.rb
+++ b/lib/archunit/extraction/analysis_snapshot.rb
@@ -9,13 +9,17 @@ module AnalysisSnapshot
source_files imports unresolved_imports unresolved_constant_references
ambiguous_constant_references
].freeze
- private_constant :COUNTERS
+ ASSOCIATION_COUNTERS = %i[
+ rails_association_sites unresolved_rails_associations ambiguous_rails_associations
+ ].freeze
+ private_constant :COUNTERS, :ASSOCIATION_COUNTERS
def self.graph(root, patterns, options, counters: nil, status: 'analyzed')
settings = {
kind: 'dependency_graph', dependency_analysis: options.dependency_analysis.to_s.freeze,
rails_imports: options.rails_imports, load_paths: options.load_paths
}
+ settings[:rails_associations] = true if options.rails_associations?
build(root, patterns, settings, graph_counters(options, counters), status)
end
@@ -28,7 +32,8 @@ def self.source(discovery, count: nil, status: 'analyzed')
end
def self.graph_counters(options, values)
- counters = COUNTERS.to_h { |key| [key, values&.fetch(key)] }
+ keys = options.rails_associations? ? COUNTERS + ASSOCIATION_COUNTERS : COUNTERS
+ counters = keys.to_h { |key| [key, values&.fetch(key)] }
unless options.constant_references?
counters[:unresolved_constant_references] = nil
counters[:ambiguous_constant_references] = nil
diff --git a/lib/archunit/extraction/constant_dependency_edge.rb b/lib/archunit/extraction/constant_dependency_edge.rb
new file mode 100644
index 0000000..3f05a06
--- /dev/null
+++ b/lib/archunit/extraction/constant_dependency_edge.rb
@@ -0,0 +1,24 @@
+# frozen_string_literal: true
+
+require_relative '../common/extraction/edge'
+
+module ArchUnit
+ module Extraction
+ # Shared source/definition evidence construction for indexed dependencies.
+ module ConstantDependencyEdge
+ def self.build(source, reference, location, kind)
+ return if source == location.source
+
+ evidence = Common::Extraction::DependencyEvidence.new(
+ source:, kind:, name: reference.name, line_number: reference.line_number,
+ end_line: reference.end_line, target_line_number: location.line_number
+ )
+ Common::Extraction::Edge.new(
+ source:, target: location.source, external: false,
+ import_kinds: [kind], evidence: [evidence]
+ )
+ end
+ end
+ private_constant :ConstantDependencyEdge
+ end
+end
diff --git a/lib/archunit/extraction/constant_index.rb b/lib/archunit/extraction/constant_index.rb
index 36e0ddf..72215d9 100644
--- a/lib/archunit/extraction/constant_index.rb
+++ b/lib/archunit/extraction/constant_index.rb
@@ -1,31 +1,44 @@
# frozen_string_literal: true
-require_relative '../common/extraction/edge'
+require_relative 'constant_dependency_edge'
require_relative 'constant_visitor'
+require_relative 'rails_association_edges'
module ArchUnit
module Extraction
# Bounded project definition index. Unknown/ambiguous names never invent file targets.
class ConstantIndex
- Location = Data.define(:source, :line_number)
+ Location = Data.define(:source, :line_number, :class_declaration)
MAX_NAMESPACE_PASSES = 8
- def initialize(analyses, profile: nil)
+ def initialize(analyses, profile: nil, rails_associations: false)
@analyses = analyses
@profile = profile
+ @rails_associations = rails_associations
@visitors = stabilized_visitors
@definitions = definition_locations
@namespaces = namespace_names(@visitors)
@inherited_namespaces = @visitors.values.flat_map(&:inherited_namespaces).to_set
end
- def edges
+ def edges(include_constants: true)
+ edges = include_constants ? constant_edges : []
+ edges.concat(association_edges) if @rails_associations
+ edges
+ end
+
+ private
+
+ def constant_edges
@visitors.flat_map do |source, visitor|
visitor.references.filter_map { |reference| resolve_edge(source, reference) }
end
end
- private
+ def association_edges
+ resolver = RailsAssociationEdges.new(@definitions, @profile)
+ @visitors.flat_map { |source, visitor| resolver.from(source, visitor.associations.sites) }
+ end
def stabilized_visitors
visitors = collect
@@ -36,12 +49,19 @@ def stabilized_visitors
end
unresolved_count = visitors.values.sum { |visitor| visitor.references.length }
@profile&.increment(:unresolved_constant_references, unresolved_count)
+ record_unstable_associations(visitors) if @rails_associations
{}
end
+ def record_unstable_associations(visitors)
+ count = visitors.values.sum { |visitor| visitor.associations.sites.length }
+ @profile&.increment(:rails_association_sites, count)
+ @profile&.increment(:unresolved_rails_associations, count)
+ end
+
def collect(namespace_names: nil)
@analyses.to_h do |source, result|
- visitor = ConstantVisitor.new(namespace_names:)
+ visitor = ConstantVisitor.new(namespace_names:, rails_associations: @rails_associations)
visitor.visit(result.value)
[source, visitor]
end
@@ -58,7 +78,10 @@ def definition_locations
map = Hash.new { |hash, key| hash[key] = [] }
@visitors.each do |source, visitor|
visitor.definitions.each do |definition|
- map[definition.name] << Location.new(source:, line_number: definition.line_number)
+ map[definition.name] << Location.new(
+ source:, line_number: definition.line_number,
+ class_declaration: definition.class_declaration
+ )
end
end
map
@@ -70,10 +93,8 @@ def resolve_edge(source, reference)
return unresolved(:unresolved_constant_references) if locations.empty?
return unresolved(:ambiguous_constant_references) if locations.map(&:source).uniq.length > 1
- location = locations.first
- return if source == location.source
-
- evidence_edge(source, reference, location)
+ kind = Common::Extraction::ImportKind::CONSTANT_REFERENCE
+ ConstantDependencyEdge.build(source, reference, locations.first, kind)
end
def resolve_name(reference)
@@ -92,18 +113,6 @@ def unresolved(counter)
@profile&.increment(counter)
nil
end
-
- def evidence_edge(source, reference, location)
- kind = Common::Extraction::ImportKind::CONSTANT_REFERENCE
- evidence = Common::Extraction::DependencyEvidence.new(
- source:, kind:, name: reference.name, line_number: reference.line_number,
- end_line: reference.end_line, target_line_number: location.line_number
- )
- Common::Extraction::Edge.new(
- source:, target: location.source, external: false,
- import_kinds: [kind], evidence: [evidence]
- )
- end
end
private_constant :ConstantIndex
end
diff --git a/lib/archunit/extraction/constant_visitor.rb b/lib/archunit/extraction/constant_visitor.rb
index 249af8e..892d99f 100644
--- a/lib/archunit/extraction/constant_visitor.rb
+++ b/lib/archunit/extraction/constant_visitor.rb
@@ -1,23 +1,28 @@
# frozen_string_literal: true
require 'prism'
+require_relative 'rails_association_calls'
+require_relative 'static_constant_name'
module ArchUnit
module Extraction
# Collects declarations and uses with Ruby's lexical (not textual path) nesting.
class ConstantVisitor < Prism::Visitor
- Definition = Data.define(:name, :line_number)
+ include StaticConstantName
+
+ Definition = Data.define(:name, :line_number, :class_declaration)
Reference = Data.define(:name, :nesting, :inherited_scope, :line_number, :end_line)
- attr_reader :definitions, :references, :inherited_namespaces
+ attr_reader :definitions, :references, :inherited_namespaces, :associations
- def initialize(namespace_names: nil)
+ def initialize(namespace_names: nil, rails_associations: false)
super()
@namespace_names = namespace_names
@definitions = []
@references = []
@nesting = []
@inherited_namespaces = []
+ @associations = RailsAssociationCalls.new if rails_associations
end
def visit_class_node(node)
@@ -86,8 +91,7 @@ def visit_namespace(node, inherited:)
return unless name
full_name = declaration_name(name)
- define_constant(full_name, node.constant_path)
- @inherited_namespaces << full_name if inherited
+ record_namespace(node, full_name, inherited)
previous = @nesting
@nesting = [full_name, *previous]
visit(node.body)
@@ -95,6 +99,14 @@ def visit_namespace(node, inherited:)
@nesting = previous if previous
end
+ def record_namespace(node, full_name, inherited)
+ define_constant(full_name, node.constant_path, class_declaration: node.is_a?(Prism::ClassNode))
+ @inherited_namespaces << full_name if inherited
+ return unless @associations && inherited && !@dynamic_scope
+
+ @associations.collect(full_name, static_name(node.superclass), node.body)
+ end
+
def declaration_name(name)
return name.delete_prefix('::') if name.start_with?('::') || @nesting.empty?
return qualify(name) unless name.include?('::')
@@ -108,10 +120,11 @@ def qualify(name)
@nesting.empty? ? name : "#{@nesting.first}::#{name}"
end
- def define_constant(name, node)
+ def define_constant(name, node, class_declaration: false)
return if @dynamic_scope
- @definitions << Definition.new(name:, line_number: node.location.start_line)
+ line_number = node.location.start_line
+ @definitions << Definition.new(name:, line_number:, class_declaration:)
end
def record_reference(name, node)
@@ -122,15 +135,6 @@ def record_reference(name, node)
line_number: node.location.start_line, end_line: node.location.end_line
)
end
-
- def static_name(node)
- return node.name.to_s if node.is_a?(Prism::ConstantReadNode)
- return unless node.is_a?(Prism::ConstantPathNode)
- return "::#{node.name}" if node.parent.nil?
-
- parent = static_name(node.parent)
- "#{parent}::#{node.name}" if parent
- end
end
private_constant :ConstantVisitor
end
diff --git a/lib/archunit/extraction/dependency_context.rb b/lib/archunit/extraction/dependency_context.rb
index b98a33f..4301022 100644
--- a/lib/archunit/extraction/dependency_context.rb
+++ b/lib/archunit/extraction/dependency_context.rb
@@ -16,7 +16,8 @@ def self.build(root:, targets:, load_paths:, profile:, options:)
load_paths
end
new(root:, targets:, load_paths:, profile:, cache: {},
- include_evidence: options.constant_references?, rails_imports: options.rails_imports,
+ include_evidence: options.constant_references? || options.rails_associations?,
+ rails_imports: options.rails_imports,
helper_load_paths: helpers)
end
diff --git a/lib/archunit/extraction/extract_dependencies.rb b/lib/archunit/extraction/extract_dependencies.rb
index a8c0117..0239597 100644
--- a/lib/archunit/extraction/extract_dependencies.rb
+++ b/lib/archunit/extraction/extract_dependencies.rb
@@ -30,15 +30,19 @@ def extract_dependencies_from(root, source_files, load_paths:, options:, profile
profile:, options:
)
- analyses = options.constant_references? ? parse_sources(root, source_files, profile) : {}
- edges = source_files.flat_map do |source|
- dependencies_for_source(source, context, analyses[source])
- end
- edges.concat(constant_edges(analyses, profile)) if options.constant_references?
+ indexed = options.constant_references? || options.rails_associations?
+ analyses = indexed ? parse_sources(root, source_files, profile) : {}
+ edges = source_edges(source_files, context, analyses)
+ edges.concat(indexed_edges(analyses, options, profile)) if indexed
edges.freeze
end
private_class_method :extract_dependencies_from
+ def source_edges(source_files, context, analyses)
+ source_files.flat_map { |source| dependencies_for_source(source, context, analyses[source]) }
+ end
+ private_class_method :source_edges
+
def profiled_target_index(root, source_files, profile)
ExtractionProfile.measure(profile, :target_index) do
internal_target_index(root, source_files)
@@ -51,12 +55,13 @@ def parse_sources(root, sources, profile)
end
private_class_method :parse_sources
- def constant_edges(analyses, profile)
+ def indexed_edges(analyses, options, profile)
ExtractionProfile.measure(profile, :constant_indexing) do
- ConstantIndex.new(analyses, profile:).edges
+ ConstantIndex.new(analyses, profile:, rails_associations: options.rails_associations?)
+ .edges(include_constants: options.constant_references?)
end
end
- private_class_method :constant_edges
+ private_class_method :indexed_edges
def dependencies_for_source(source, context, parse_result)
imports = extract_imports_from(
diff --git a/lib/archunit/extraction/extraction_profile.rb b/lib/archunit/extraction/extraction_profile.rb
index 2b82a99..24164aa 100644
--- a/lib/archunit/extraction/extraction_profile.rb
+++ b/lib/archunit/extraction/extraction_profile.rb
@@ -25,6 +25,9 @@ class ExtractionProfile
unresolved_imports
unresolved_constant_references
ambiguous_constant_references
+ rails_association_sites
+ unresolved_rails_associations
+ ambiguous_rails_associations
resolution_cache_hits
resolution_cache_misses
raw_edges
diff --git a/lib/archunit/extraction/rails_association_calls.rb b/lib/archunit/extraction/rails_association_calls.rb
new file mode 100644
index 0000000..d591c33
--- /dev/null
+++ b/lib/archunit/extraction/rails_association_calls.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+require_relative 'rails_association_options'
+
+module ArchUnit
+ module Extraction
+ # Collects direct Active Record-style class-body calls without walking into other receivers.
+ class RailsAssociationCalls
+ MACROS = %i[belongs_to has_one has_many has_and_belongs_to_many].freeze
+ BASES = %w[ActiveRecord::Base ApplicationRecord].freeze
+ Site = Data.define(:model, :name, :line_number, :end_line)
+ private_constant :MACROS, :BASES, :Site
+
+ attr_reader :sites
+
+ def initialize
+ @sites = []
+ end
+
+ def collect(model, superclass, body)
+ return unless BASES.include?(superclass&.delete_prefix('::'))
+ return unless body.is_a?(Prism::StatementsNode)
+
+ body.body.each do |statement|
+ next unless macro_call?(statement)
+
+ @sites << site(model, statement)
+ end
+ end
+
+ private
+
+ def macro_call?(node)
+ return false unless node.is_a?(Prism::CallNode) && MACROS.include?(node.name)
+
+ !node.safe_navigation? && (node.receiver.nil? || node.receiver.is_a?(Prism::SelfNode))
+ end
+
+ def site(model, node)
+ literal = RailsAssociationOptions.explicit_literal(node.arguments&.arguments || [])
+ Site.new(model:, name: literal&.unescaped, line_number: node.message_loc.start_line,
+ end_line: (literal || node).location.end_line)
+ end
+ end
+ private_constant :RailsAssociationCalls
+ end
+end
diff --git a/lib/archunit/extraction/rails_association_edges.rb b/lib/archunit/extraction/rails_association_edges.rb
new file mode 100644
index 0000000..5ec9e90
--- /dev/null
+++ b/lib/archunit/extraction/rails_association_edges.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+require_relative 'constant_dependency_edge'
+
+module ArchUnit
+ module Extraction
+ # Bounded Active Record name lookup over the same definitions as constant analysis.
+ class RailsAssociationEdges
+ def initialize(definitions, profile)
+ @definitions = definitions
+ @profile = profile
+ end
+
+ def from(source, sites)
+ @profile&.increment(:rails_association_sites, sites.length)
+ sites.filter_map { |site| resolve(source, site) }
+ end
+
+ private
+
+ def resolve(source, site)
+ locations = candidate_locations(site)
+ return unmodeled(:unresolved_rails_associations) if locations.empty?
+ return unmodeled(:ambiguous_rails_associations) if locations.map(&:source).uniq.length > 1
+
+ location = locations.find(&:class_declaration)
+ return unmodeled(:unresolved_rails_associations) unless location
+
+ ConstantDependencyEdge.build(source, site, location, Common::Extraction::ImportKind::RAILS_ASSOCIATION)
+ end
+
+ def candidate_locations(site)
+ return [] unless site.name
+
+ name = candidates(site).find { |candidate| @definitions.key?(candidate) }
+ @definitions.fetch(name, [])
+ end
+
+ def candidates(site)
+ name = site.name
+ return [name.delete_prefix('::')] if name.start_with?('::')
+
+ parts = site.model.split('::')
+ prefixed = parts.length.downto(1).map do |length|
+ "#{parts.take(length).join('::')}::#{name}"
+ end
+ parts.last == name ? [name, *prefixed] : [*prefixed, name]
+ end
+
+ def unmodeled(counter)
+ @profile&.increment(counter)
+ nil
+ end
+ end
+ private_constant :RailsAssociationEdges
+ end
+end
diff --git a/lib/archunit/extraction/rails_association_options.rb b/lib/archunit/extraction/rails_association_options.rb
new file mode 100644
index 0000000..a717b40
--- /dev/null
+++ b/lib/archunit/extraction/rails_association_options.rb
@@ -0,0 +1,57 @@
+# frozen_string_literal: true
+
+require 'prism'
+
+module ArchUnit
+ module Extraction
+ # Recognizes explicit literal keyword options, not arbitrary Ruby option expressions.
+ module RailsAssociationOptions
+ CLASS_NAME = /\A(?:::)?[A-Z]\w*(?:::[A-Z]\w*)*\z/
+ private_constant :CLASS_NAME
+
+ def self.explicit_literal(arguments)
+ return unless supported_arguments?(arguments)
+
+ options = keyword_options(arguments.last)
+ return if options.nil? || indirect?(options)
+
+ class_name_literal(options['class_name'])
+ end
+
+ def self.class_name_literal(value)
+ return unless value.is_a?(Prism::StringNode) || value.is_a?(Prism::SymbolNode)
+
+ name = value.unescaped
+ value if name.ascii_only? && CLASS_NAME.match?(name)
+ end
+
+ def self.supported_arguments?(arguments)
+ return false unless arguments.first.is_a?(Prism::SymbolNode)
+ return false unless arguments.last.is_a?(Prism::KeywordHashNode)
+
+ arguments.length == 2 ||
+ (arguments.length == 3 && arguments[1].is_a?(Prism::LambdaNode))
+ end
+
+ def self.keyword_options(node)
+ node.elements.each_with_object({}) do |entry, options|
+ return nil unless entry.is_a?(Prism::AssocNode) && entry.key.is_a?(Prism::SymbolNode)
+
+ key = entry.key.unescaped
+ return nil if options.key?(key)
+
+ options[key] = entry.value
+ end
+ end
+
+ def self.indirect?(options)
+ return true if %w[through as source_type anonymous_class].any? { |key| options.key?(key) }
+
+ polymorphic = options['polymorphic']
+ polymorphic && !polymorphic.is_a?(Prism::FalseNode) && !polymorphic.is_a?(Prism::NilNode)
+ end
+ private_class_method :supported_arguments?, :keyword_options, :class_name_literal, :indirect?
+ end
+ private_constant :RailsAssociationOptions
+ end
+end
diff --git a/lib/archunit/extraction/static_constant_name.rb b/lib/archunit/extraction/static_constant_name.rb
new file mode 100644
index 0000000..e997da0
--- /dev/null
+++ b/lib/archunit/extraction/static_constant_name.rb
@@ -0,0 +1,22 @@
+# frozen_string_literal: true
+
+require 'prism'
+
+module ArchUnit
+ module Extraction
+ # Converts a literal Prism constant path to a name without following dynamic receivers.
+ module StaticConstantName
+ private
+
+ def static_name(node)
+ return node.name.to_s if node.is_a?(Prism::ConstantReadNode)
+ return unless node.is_a?(Prism::ConstantPathNode)
+ return "::#{node.name}" if node.parent.nil?
+
+ parent = static_name(node.parent)
+ "#{parent}::#{node.name}" if parent
+ end
+ end
+ private_constant :StaticConstantName
+ end
+end
diff --git a/scripts/check_rails_associations.rb b/scripts/check_rails_associations.rb
new file mode 100644
index 0000000..1640ca2
--- /dev/null
+++ b/scripts/check_rails_associations.rb
@@ -0,0 +1,68 @@
+# frozen_string_literal: true
+
+require 'archunit'
+require 'archunit/cli'
+require 'json'
+require 'pathname'
+require 'stringio'
+require 'tmpdir'
+
+def write_association_fixture(root)
+ root.join('Gemfile').write("raise 'do not evaluate Gemfile'")
+ root.join('client.rb').write(<<~RUBY)
+ class Client < ApplicationRecord
+ belongs_to :store, class_name: 'Storage::Store'
+ has_many :items
+ end
+ raise 'do not execute model source'
+ RUBY
+ root.join('store.rb').write("module Storage; class Store; end; end\nraise 'do not execute'")
+ write_association_config(root)
+end
+
+def write_association_config(root)
+ root.join('.archunit.rb').write(<<~RUBY)
+ rule('Storage is private') do
+ project_files.in_path('client.rb').should_not.depend_on_files.in_path('store.rb')
+ end
+ RUBY
+end
+
+def run_association_cli(root, *flags, format: 'json')
+ output = StringIO.new
+ errors = StringIO.new
+ status = ArchUnit::CLI.run(['check', '--format', format, *flags],
+ out: output, err: errors, cwd: root.to_s)
+ abort errors.string unless errors.string.empty?
+ [status, format == 'json' ? JSON.parse(output.string) : output.string]
+end
+
+def verify_association_cli(root)
+ code, old = run_association_cli(root, '--rails-associations', '--no-rails-associations')
+ abort 'association analysis silently enabled' unless code.zero? && !old.key?('rails_associations')
+
+ code, report = run_association_cli(root, '--rails-associations')
+ abort 'expected a violation' unless code == 1 && report.fetch('rails_associations')
+
+ verify_association_counters(report.dig('analysis', 'scopes', 0))
+ _, text = run_association_cli(root, '--rails-associations', format: 'text')
+ abort 'text diagnostics missing' unless text.include?('association class names: enabled')
+end
+
+def verify_association_counters(scope)
+ expected = { 'rails_association_sites' => 2, 'unresolved_rails_associations' => 1,
+ 'ambiguous_rails_associations' => 0, 'unresolved_constant_references' => nil }
+ counters = scope.fetch('counters').slice(*expected.keys)
+ return if scope.fetch('rails_associations') && counters == expected
+
+ abort "unexpected association counters: #{scope.inspect}"
+end
+
+Dir.mktmpdir('archunit-installed-rails-associations') do |directory|
+ root = Pathname.new(directory)
+ write_association_fixture(root)
+ verify_association_cli(root)
+ puts 'Explicit Rails association check and diagnostics passed without booting Rails or source.'
+ensure
+ ArchUnit.clear_graph_cache
+end
diff --git a/spec/benchmark/performance_study_spec.rb b/spec/benchmark/performance_study_spec.rb
index b382a1f..9ead86e 100644
--- a/spec/benchmark/performance_study_spec.rb
+++ b/spec/benchmark/performance_study_spec.rb
@@ -4,6 +4,7 @@
require 'tmpdir'
require 'yaml'
require_relative '../../benchmark/study/run'
+require_relative '../../benchmark/study/rails_association_cost'
RSpec.describe PerformanceStudy::Runner do
it 'keeps the isolated path-gem lock synchronized with the candidate version' do
@@ -34,6 +35,13 @@
expect { described_class.run(trials: 0) }.to raise_error(ArgumentError)
end
+ it 'validates paired association graphs with both sample orders and no speed gates' do
+ groups = PerformanceStudy::RailsAssociationCost.run(pairs: 4, trials: 2)
+ expect(groups.map { |group| group.map { |sample| sample[:enabled] } })
+ .to eq([[false, true], [true, false]])
+ expect(groups.flatten.map { |sample| sample[:cold][:allocated_objects] }).to all(be_positive)
+ end
+
it 'uses bounded read-only Linux CI with immutable sources, research-only deps and artifacts' do
path = File.expand_path('../../.github/workflows/performance-study.yml', __dir__)
workflow = YAML.safe_load_file(path, aliases: true)
diff --git a/spec/ci/workflow_spec.rb b/spec/ci/workflow_spec.rb
index 2a63c74..c2d3b06 100644
--- a/spec/ci/workflow_spec.rb
+++ b/spec/ci/workflow_spec.rb
@@ -48,6 +48,7 @@
'ruby scripts/check_namespace_receivers.rb',
'ruby scripts/check_static_paths.rb',
'ruby scripts/check_rails_imports.rb',
+ 'ruby scripts/check_rails_associations.rb',
'ruby scripts/check_source_exclusions.rb',
'ruby scripts/check_analysis_diagnostics.rb',
'ruby scripts/check_baselines.rb',
@@ -107,6 +108,9 @@
it 'exercises opt-in Rails imports on every supported compatibility platform' do
expect(steps).to include(include('run' => 'bundle exec ruby scripts/check_rails_imports.rb'))
+ expect(steps).to include(
+ include('run' => 'bundle exec ruby scripts/check_rails_associations.rb')
+ )
end
it 'exercises caller-owned source policies on every compatibility platform' do
diff --git a/spec/cli/analysis_spec.rb b/spec/cli/analysis_spec.rb
index 2ce8782..e602d63 100644
--- a/spec/cli/analysis_spec.rb
+++ b/spec/cli/analysis_spec.rb
@@ -125,6 +125,18 @@ def perform_check(_options) = []
expect(errors).to include('source_files=unavailable', 'Analysis: partial')
end
+ it 'reports unavailable association counts when an enabled analysis cannot parse source' do
+ @root.join('broken.rb').write('class Broken <')
+ code, payload = invoke('--rails-associations')
+ expect(code).to eq(2)
+ scope = payload.dig('analysis', 'scopes', 0)
+ expect(scope).to include('rails_associations' => true, 'status' => 'error')
+ expect(scope['counters']).to include(
+ 'rails_association_sites' => nil, 'unresolved_rails_associations' => nil,
+ 'ambiguous_rails_associations' => nil
+ )
+ end
+
it 'keeps different analysis roots and source policies separate rather than double counting' do
other = @root.dirname.join('other')
other.mkpath
diff --git a/spec/cli/baseline_spec.rb b/spec/cli/baseline_spec.rb
index 46e9f74..d98567f 100644
--- a/spec/cli/baseline_spec.rb
+++ b/spec/cli/baseline_spec.rb
@@ -128,6 +128,16 @@ def repeated_rule(count)
RUBY
end
+ it 'does not reuse debt with association analysis on but preserves disabled fingerprints' do
+ create
+ expect(check('--no-rails-associations').first).to eq(0)
+ code, report = check('--rails-associations')
+ expect(code).to eq(1)
+ expect(report['baseline']).to include(
+ 'accepted_count' => 0, 'new_count' => 1, 'stale_count' => 1
+ )
+ end
+
it 'consumes duplicate fingerprints one occurrence at a time' do
repeated_rule(2)
expect(create.first).to eq(0)
diff --git a/spec/common/extraction/import_kind_spec.rb b/spec/common/extraction/import_kind_spec.rb
index 797af4b..9adfb5e 100644
--- a/spec/common/extraction/import_kind_spec.rb
+++ b/spec/common/extraction/import_kind_spec.rb
@@ -8,7 +8,8 @@
:autoload,
:load,
:require_dependency,
- :constant_reference
+ :constant_reference,
+ :rails_association
)
end
diff --git a/spec/common/fluentapi/check_options_spec.rb b/spec/common/fluentapi/check_options_spec.rb
index 3a7ecbe..5d1247a 100644
--- a/spec/common/fluentapi/check_options_spec.rb
+++ b/spec/common/fluentapi/check_options_spec.rb
@@ -1,6 +1,15 @@
# frozen_string_literal: true
RSpec.describe ArchUnit::Common::FluentApi::CheckOptions do
+ it 'keeps explicit Rails association analysis separately opt-in and boolean' do
+ options = described_class.new
+ expect(options).not_to be_rails_associations
+ expect(options.with(rails_associations: true)).to be_rails_associations
+ expect(options.with(rails_imports: true)).not_to be_rails_associations
+ expect { described_class.new(rails_associations: 'yes') }
+ .to raise_error(ArgumentError, 'rails_associations must be true or false')
+ end
+
it 'defaults to strict empty tests with logging disabled and cache reuse' do
options = described_class.new
diff --git a/spec/extraction/rails_associations_spec.rb b/spec/extraction/rails_associations_spec.rb
new file mode 100644
index 0000000..9d87503
--- /dev/null
+++ b/spec/extraction/rails_associations_spec.rb
@@ -0,0 +1,210 @@
+# frozen_string_literal: true
+
+require 'json'
+require 'pathname'
+require 'tmpdir'
+
+RSpec.describe 'Explicit Rails associations' do
+ around do |example|
+ Dir.mktmpdir('archunit-associations') do |directory|
+ @root = Pathname.new(directory)
+ write('Gemfile', "raise 'do not load Gemfile'")
+ example.run
+ ensure
+ ArchUnit.clear_graph_cache
+ end
+ end
+
+ def write(path, contents)
+ path = @root.join(path)
+ path.dirname.mkpath
+ path.write(contents)
+ end
+
+ def model(code, superclass: '::ActiveRecord::Base')
+ write('packs/api/app/models/requests/order.rb', <<~RUBY)
+ class Requests::Order < #{superclass}
+ #{code}
+ end
+ RUBY
+ end
+
+ def graph(**settings)
+ ArchUnit::Extraction.extract_graph(@root, options: ArchUnit::CheckOptions.new(**settings))
+ end
+
+ def association_edges(graph)
+ graph.select { |edge| edge.import_kinds.include?(:rails_association) }
+ end
+
+ def associations
+ association_edges(graph(rails_associations: true))
+ end
+
+ def counted_graph(**settings)
+ profile = ArchUnit::Extraction::ExtractionProfile.new
+ options = ArchUnit::CheckOptions.new(rails_associations: true, **settings)
+ graph = ArchUnit::Extraction.extract_graph(@root, options:, profile:)
+ [graph, profile.counters]
+ end
+
+ it 'detects the issue probe only with the new setting and uses the existing rule' do
+ model("belongs_to :store, class_name: 'Retrieval::Store'")
+ store = 'packs/storage/app/models/retrieval/store.rb'
+ write(store, "module Retrieval; class Store; end; end\nraise 'do not execute target'")
+ rule = ArchUnit.files(@root).in_path('packs/api/**').should_not
+ .depend_on_files.in_path('packs/storage/**')
+
+ expect(rule.check).to be_empty
+ legacy = ArchUnit::CheckOptions.new(dependency_analysis: :imports_and_constants,
+ rails_imports: true)
+ expect(rule.check(legacy)).to be_empty
+ [ArchUnit::CheckOptions.new, legacy].each do |options|
+ violations = rule.check(options.with(rails_associations: true))
+ expect(violations.length).to eq(1)
+ edge = violations.first.dependency.cumulated_edges.first
+ expect(edge.target).to eq(store)
+ expect(edge.import_kinds).to eq([:rails_association])
+ expect(edge.evidence.first.to_h).to include(
+ kind: :rails_association, name: 'Retrieval::Store', line_number: 2, target_line_number: 1
+ )
+ end
+ end
+
+ it 'recognizes all four macros, a lambda scope, self, and literal symbol values' do
+ model(<<~RUBY, superclass: 'ApplicationRecord')
+ belongs_to :account, class_name: 'Account'
+ has_one :item, "class_name": :Account
+ self.has_many :items, -> { where(current: true) }, class_name: 'Account'
+ has_and_belongs_to_many :others, :class_name => 'Account'
+ RUBY
+ write('lib/account.rb', 'class Account; end')
+
+ expect(associations.map(&:target)).to eq(['lib/account.rb'])
+ edge = associations.first
+ expect(edge.evidence.map(&:line_number)).to eq([2, 3, 4, 5])
+ expect(edge.evidence.map(&:name)).to eq(%w[Account Account Account Account])
+ end
+
+ it 'tries full model-name prefixes, honors root qualification, and falls back across roots' do
+ model(<<~RUBY)
+ belongs_to :local, class_name: 'Store'
+ belongs_to :root, class_name: '::Store'
+ belongs_to :otherwise, class_name: 'Services::Widget'
+ RUBY
+ write('packs/api/names.rb', 'module Requests; module Services; end; class Store; end; end')
+ write('packs/other/root.rb', 'class Store; end')
+ write('packs/other/service.rb', 'module Services; class Widget; end; end')
+ expect(associations.map(&:target)).to contain_exactly(
+ 'packs/api/names.rb', 'packs/other/root.rb', 'packs/other/service.rb'
+ )
+ end
+
+ it 'keeps evidence from the macro line through the literal, not unrelated option lines' do
+ model(<<~RUBY)
+ belongs_to :account,
+ class_name: 'Account',
+ optional: true
+ RUBY
+ write('lib/account.rb', "class Account\nend")
+ expect(associations.first.evidence.first.to_h).to include(
+ name: 'Account', line_number: 2, end_line: 3, target_line_number: 1
+ )
+ end
+
+ it 'prefers model-local targets except that the model basename tries root first' do
+ model(<<~RUBY)
+ belongs_to :nested, class_name: 'Store'
+ belongs_to :same_basename, class_name: 'Order'
+ class Store; end
+ RUBY
+ write('lib/root.rb', 'class Order; end')
+ write('lib/fallback.rb', 'module Requests; class Store; end; end')
+ expect(associations.map(&:target)).to eq(['lib/root.rb'])
+ end
+
+ it 'does not guess past ambiguous or non-class candidates and counts unsupported sites' do
+ model(<<~'RUBY')
+ belongs_to :dup, class_name: 'Duplicate'
+ belongs_to :missing, class_name: 'Missing'
+ belongs_to :unknown, class_name: "Thing#{ENV.fetch('TYPE')}"
+ has_many :indirect, class_name: 'Target', through: :joins
+ belongs_to :indirect, class_name: 'Target', polymorphic: true
+ has_many :polymorphic_children, class_name: 'Target', as: :owner
+ has_many :inferred
+ has_many :duplicate, class_name: 'Target', :"class_name" => 'Other'
+ has_many :expanded, **{ class_name: 'Target' }
+ has_many :bad_key, "class_name" => 'Target'
+ has_many :bad_name, class_name: 'Target.call'
+ has_many :path_shadow, class_name: 'Target'
+ has_many :expression, class_name: Target
+ has_many :binary, class_name: "\xff"
+ RUBY
+ write('lib/one.rb', "module Requests; class Duplicate; end; Target = 'not a class'; end")
+ write('lib/two.rb', 'module Requests; class Duplicate; end; end')
+ write('lib/fallback.rb', 'class Duplicate; end; class Target; end')
+
+ edges, counts = counted_graph
+ expect(association_edges(edges)).to be_empty
+ expect(counts).to include(rails_association_sites: 14, unresolved_rails_associations: 13,
+ ambiguous_rails_associations: 1)
+ end
+
+ it 'ignores ordinary strings, comments, unrelated classes/receivers and indirect calls' do
+ model(<<~RUBY)
+ OPTIONS = { class_name: 'Target' }
+ # belongs_to :comment, class_name: 'Target'
+ unrelated.has_many :other, class_name: 'Target'
+ self&.has_many :safe, class_name: 'Target'
+ custom_association :extension, class_name: 'Target'
+ def call
+ belongs_to :nested_call, class_name: 'Target'
+ end
+ configure { has_many :inside_block, class_name: 'Target' }
+ RUBY
+ write('lib/other.rb', "class Other; has_many :target, class_name: 'Target'; end")
+ write('lib/empty.rb', 'class Empty < ApplicationRecord; end')
+ write('lib/target.rb', 'class Target; end')
+ expect(associations).to be_empty
+ expect(counted_graph(clear_cache: true).last).to include(rails_association_sites: 0)
+ end
+
+ it 'merges repeated sites, ordinary references and imports with stable evidence' do
+ model(<<~RUBY)
+ require_relative 'store'
+ belongs_to :store, class_name: '::Store', polymorphic: false
+ has_one :second, class_name: '::Store'
+ def build
+ ::Store.new
+ end
+ RUBY
+ write('packs/api/app/models/requests/store.rb', "class Store\nend")
+ options = ArchUnit::CheckOptions.new(
+ rails_associations: true, dependency_analysis: :imports_and_constants
+ )
+ report = ArchUnit.project_graph(@root).with_check_options(options)
+ edges = JSON.parse(report.to_json).fetch('edges').select do |item|
+ item['import_kinds'].include?('rails_association')
+ end
+ expect(edges.length).to eq(1)
+ edge = edges.first
+ expect(edge['import_kinds']).to eq(%w[constant_reference rails_association require_relative])
+ expect(edge['evidence'].map { |item| item['line_number'] }).to eq([2, 6, 3, 4])
+ expect(edge['evidence'].map { |item| item['target_line_number'] }).to eq([nil, 1, 1, 1])
+ end
+
+ it 'partitions cache identity and excludes unavailable definition files' do
+ model("belongs_to :store, class_name: 'Store'")
+ write('packs/storage/store.rb', 'class Store; end')
+ plain = graph
+ enabled = graph(rails_associations: true)
+ expect(enabled).not_to equal(plain)
+ expect(graph(rails_associations: true)).to equal(enabled)
+ expect(graph(rails_associations: true, clear_cache: true)).not_to equal(enabled)
+ expect(graph).to equal(plain)
+ edges, counters = counted_graph(source_exclusions: ['packs/storage/**'])
+ expect(edges.none?(&:external)).to be(true)
+ expect(association_edges(edges)).to be_empty
+ expect(counters).to include(unresolved_rails_associations: 1)
+ end
+end