0

I've created new simple Rails 6 application for test reasons.

In config/environments/development.rb

...
config.cache_classes = false
config.eager_load = false
...

/app/controllers/articles_controller.rb

class ArticlesController < ApplicationController
  def index
    Foo.test_foo
  end
end

/app/models/foo.rb

module Foo
  class << self
    def test_foo
      Bar.test_bar
    end
  end
end

/app/models/foo/bar.rb

module Foo
  class Bar
    class << self
      def test_bar
        puts "111"
      end
    end
  end
end

After calling articles controller i get error

NameError (uninitialized constant Bar):

app/models/foo.rb:4:in `test_foo'
app/controllers/articles_controller.rb:3:in `index'

When i enable eager loading(config.eager_load = true) - all become ok.

Second solve - using full namespace path Foo::Bar in /app/models/foo.rb like a

module Foo
  class << self
    def test_foo
      Foo::Bar.test_bar
    end
  end
end

And, ofcourse, i can use direct "require", but don't want it.

Is there way to use shorthands for nested classes without eager load and without using "require"?

2
  • 1
    This is a known issue with the classic autoloader. I would use the workaround until you can upgrade and use Zeitwerk instead. blog.kiprosh.com/… Commented Aug 24, 2024 at 14:37
  • When in doubt require dependencies. Rails conveniences had for some odd reason caused some developers to believe that the need to require is somehow an anti pattern, whereas in reality it is exactly the opposite. Relying on a mechanism like autoload or even the much improved process of zeitwerk does not solve all ills. These mechanisms, in my opinion, are more like an opinionated rubocop then anything else. I am not saying structured code organization is a bad thing, nor am I saying a progressive linter damages the code but it does cause people to forget the basics. Commented Aug 26, 2024 at 13:52

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.