Ruby: is it acceptable to put more than one class in a file?

后端 未结 3 1664
野趣味
野趣味 2021-02-13 14:33

This might be a bit of an esoteric question, but I just want to know what best practices are on this issue.

相关标签:
3条回答
  • 2021-02-13 14:48

    Personally, I tend to avoid that for large classes for purely organisational reasons - it is easier to navigate large classes when they are separated. However, if classes are small, related (e.g. all exceptions in one file rather than in a bunch of them) or meta-generated (e.g. with eval), then yes - they are in one file.

    It depends on what kind of application you are developing and how you want your code to be structured so that it is easy to understand, document and modify.

    Ruby itself does not care much about it, you can have your entire app in a single file, if you want. Rails on the contrary - due to magic loading of files based on class names.

    0 讨论(0)
  • 2021-02-13 15:01

    Generally it is best practice to keep them in separate files that include the class name in the file name. This keeps your project better oragnized and makes it easier for someone else to navigate your structure.

    0 讨论(0)
  • 2021-02-13 15:02

    Yes, it is generally acceptable because it doesn't violate any principles of the Ruby language itself but it ultimately depends on the practices of your target audience or framework. (For example, Rails likes your classes to be one-per-file.)

    However, if you are grouping classes with related functionality into a single file then you should also consider making them part of the same module for a namespace.

    0 讨论(0)
提交回复
热议问题