Why is Rails trying to guess the file name when I turn on the module?

I have the following setup in which one of my classes includes a module located in another file

The main thing to note is that the module MyBardoes not live in a file with a similar name. He lives in my_foo.rb.

my_foo.rb

module MyBar
  def self.test
    "This is a test string"
  end
end

some_class.rb

require 'my_foo'

class SomeClass
  include MyBar

  def initialize
    puts MyBar.test
  end
end

When I run this, I get NameError

NameError - uninitialized constant MyBar

Rails seems to be trying to be smart and suggest that since the module name MyBar, it should be located in a file with the name my_bar.rb.

I tried to test this theory by changing the name to what it expects, and it suddenly worked correctly

my_foo.rb (renamed)-> my_bar.rb

Question:

  • Why does Rails do this? It seems like it's too much. I understand that this is a “configuration convention”, but there are several good reasons why the file name does not match the module name.

  • ?

+4
2

, Rails.

/, /lib/.

, my_foo.rb /lib/ : require 'lib/my_foo'

, Rails, . Rails .

+2

app $LOAD_PATH ( ).

, , lib (lib $LOAD_PATH).

app, , , require Rails.root.join('app', 'models', 'my_foo.rb').to_s. , , .

+1

Source: https://habr.com/ru/post/1608915/


All Articles