Project

General

Profile

Feature #9768

Method that is visible only within a certain module/class

Added by sawa (Tsuyoshi Sawada) over 5 years ago. Updated about 5 years ago.

Status:
Assigned
Priority:
Normal
Target version:
-
[ruby-core:62134]

Description

Some frameworks/libraries monkeypatch their own methods on Ruby core classes like String, Hash, Array, etc., and that is often causing problems/concerns of name conflict.

Seeing that these custom methods are used only in the context of a certain module/class, I request for a way to define a method (foo) on a module/class (A) so that it will be visible only from within a specified module/class (B) or its descendants. The following illustrates this situation:

A.new.foo # => undefined

class B
  A.new.foo # => defined
  def bar
    A.new.foo # => defined
  end
  def self.baz
    A.new.foo # => defined
  end
end

class C < B
  A.new.foo # => defined
  def bar
    A.new.foo # => defined
  end
  def self.baz
    A.new.foo # => defined
  end
end

I do not have a certain syntax for this in mind, but I think it can be made much simpler, compared to the complicated syntax of refinement.

This is reminiscent of refinement, but they are pretty much different.

Refinement's purpose is to let certain methods be accessible from only a certain file. A typical use case would be a library developer defining their methods to be used from within the library and making such methods inaccessible from the end user.

On the other hand, the idea I am proposing here is for making method accessible from any file, but only within a certain module/class. A typical use case would be defining a method to be used by an end user, but only from within a context of certain module/class.

History

Updated by shugo (Shugo Maeda) about 5 years ago

  • Status changed from Open to Assigned
  • Assignee set to matz (Yukihiro Matsumoto)

Tsuyoshi Sawada wrote:

Seeing that these custom methods are used only in the context of a certain module/class, I request for a way to define a method (foo) on a module/class (A) so that it will be visible only from within a specified module/class (B) or its descendants. The following illustrates this situation:

The original proposal of Refinements was able to be used in such a situation, but refinement inheritance in class hierarchies and refinement activation for reopened module definitions were removed (see https://bugs.ruby-lang.org/issues/4085#note-141 and other comments).

Matz said that a refinement should be activated only in a lexical scope explicitly specified, because users might be confused if methods are refined implicitly.

Also available in: Atom PDF