Project

General

Profile

Actions

Bug #19405

closed

Prevent Use of include CustomModule in a Nested Class

Added by kyonides (Edwin Acuña) about 1 year ago. Updated about 1 year ago.

Status:
Rejected
Assignee:
-
Target version:
-
ruby -v:
ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-linux-gnu]
[ruby-core:112193]

Description

Bug present ever since Ruby 1.8.
Tested in Ruby 2.7 and 3.0 as well.

I would like to request the developers to prevent any person from doing something as illogical and useless as the code I have provided you with right below.

module MyModule
  class MyClass
    A = 'A'
    B = 'B'
    include MyModule
  end
end

If you print something like:

puts MyModule::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::MyClass::B

Ruby will let you do it!

Why is it possible to chain the calls to MyClass class forever and ever?
It should throw an error for including the very same module and class where the constants are nested.

Proposed Error Class:

"ModuleError: Class nested in module %s cannot call include method to add the same module."

Or something the like. =_=¡

Updated by jeremyevans0 (Jeremy Evans) about 1 year ago

  • Status changed from Open to Rejected

This is not a bug, this is expected behavior. It is true in Ruby even if you don't define any classes:

Object::Object::Object::Object::Object::Object::Object::Object::Object::Object::Object::Object::Object::Object::Object::Object::Object::Object
# => Object

If you want to prevent this, you could override include:

module MyModule
  class MyClass
    A = 'A'
    B = 'B'

    def self.include(mod)
      raise if mod.const_get(name) == self
      super
    end

    include MyModule
  end
end

You can even try to handle this globally:

class Module
  def append_features(mod)
    raise if const_get(mod.name) == mod
    super
  end
end

That only handles the direct inclusion case, it won't handle more complex cases, or even other simple cases such as module MyModule; MyModule = self end.

In general, you should just accept that this is how Ruby is, and it isn't a problem.

Actions

Also available in: Atom PDF

Like0
Like0