You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Hi, I have question regarding the best practices for file structure (ref)
In my Rails project, I organize lengthy constant declarations into separate files in order to keep classes clean.
For example:
# app/models/foo.rb
class Foo
end
# app/models/foo/constants.rb
class Foo
MY_CONSTANT = ...
end
# elsewhere in app
Foo::MY_CONSTANT
However, Zeitwerk doesn't like this because it maps from filenames to constants, and requires those constants to be defined (ref). So, if you try to load the code above, you'll get an error message:
Excpeted file app/models/foo/constants.rb to define constant Foo::Constants, but didn't.
The obvious solution here is to define Foo::Constants:
# app/models/foo/constants.rb
class Foo
module Constants
MY_CONSTANT = ...
end
end
# elsewhere in app
Foo::Constants::MY_CONSTANT
But, I have a lot of files like foo/constants.rb, and I am lazy. Are there any other alternatives for getting zeitwerk to autoload files like this?
I appreciate the work the team has done in this gem! It's a big improvement.
The text was updated successfully, but these errors were encountered:
One possible solution that would flow well with everything would be to define Foo::Constants:
# app/models/foo/constants.rbmoduleFoo::ConstantsMY_CONSTANT= ...
end
and then include that one in Foo:
# app/models/foo.rbmoduleFooincludeConstantsend
That works because to resolve Foo:: MY_CONSTANT Ruby looks the ancestors of Foo up, follows the conventions, works well with reloading.... Also, anyone opening app/models/foo.rb sees clearly that you're injecting constants into Foo.
Hi, I have question regarding the best practices for file structure (ref)
In my Rails project, I organize lengthy constant declarations into separate files in order to keep classes clean.
For example:
However, Zeitwerk doesn't like this because it maps from filenames to constants, and requires those constants to be defined (ref). So, if you try to load the code above, you'll get an error message:
Excpeted file app/models/foo/constants.rb to define constant Foo::Constants, but didn't.
The obvious solution here is to define
Foo::Constants
:But, I have a lot of files like
foo/constants.rb
, and I am lazy. Are there any other alternatives for getting zeitwerk to autoload files like this?I appreciate the work the team has done in this gem! It's a big improvement.
The text was updated successfully, but these errors were encountered: