Accidentally exposing methods as public in `class << self` is surprisingly easy
class << self block. However, this syntax has a subtle gotcha: methods defined inside the block are public by default, even if the block is nested within a private section.class MyClass
private
class << self
def my_method # ← this is a public method 😱
# ...
end
end
endclass << self, Ruby opens the singleton class of the object (in this case, your class). While methods defined in a normal class body respect the current visibility context (private, protected, or public), class << self resets the default visibility to public. As a result, any method defined there will be public unless explicitly declared otherwise.private explicitlyclass << self block, explicitly set the visibility to private:class MyClass
private
class << self
private # ← you have to declare `private` again
def my_method # ← now this method is actually private!
# ...
end
end
endprivate_class_methodprivate_class_method to set its visibility:class MyClass
class << self
def my_method
# ...
end
end
private_class_method :my_method
end