Skip to content

Conversation

@unurgunite
Copy link

@unurgunite unurgunite commented Nov 6, 2025

Description

YARD incorrectly marked singleton method definitions (def self.x) as private when a bare private appeared earlier in the class body. This problem was originally described here (#1496). Ruby semantics say a bare access modifier affects only the current def-target:

  • class body: affects instance methods only
  • inside class << self: affects class methods only
  • def self.x in a class body remains public unless:
    • private_class_method is used, or
    • private appears inside class << self

This PR brings YARD in line with Ruby.

Behavior change:

  • Bare private/public/protected now only affect methods whose scope matches the current def-target.
  • @!visibility directive continues to apply regardless of method scope (as before), since it’s a documentation control.
  • Explicit statements private :foo/public :foo are unaffected.
  • private_class_method/public_class_method handlers continue to set exact visibilities.

So, the code from the issue now outputs correctly:

require 'yard'

code = <<~CODE
  class T
    def m1
      T.m2
    end

    private

    def self.m2
      print 123
    end

    class << self
      private

      def m3; end
    end
  end
CODE

def detect_private_methods(code)
  YARD.parse_string(code)
  YARD::Registry.all(:class).map do |class_obj|
    class_obj.meths(inherited: false).map do |method_obj|
      if method_obj.scope == :class && method_obj.visibility == :private
        puts "Method #{method_obj.name} is a #{method_obj.visibility} #{method_obj.scope} method!"
      end
    end
  end
end

detect_private_methods(code)
# Method m3 is a private class method!
# => [[nil, nil, nil]]

Completed Tasks

  • I have read the Contributing Guide.
  • The pull request is complete (implemented / written).
  • Git commits have been cleaned up (squash WIP / revert commits).
  • I wrote tests and ran bundle exec rake locally (if code is attached to PR).

@unurgunite unurgunite force-pushed the fix-private-methods-detection branch from dfe4d17 to 63e7995 Compare November 6, 2025 21:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant