0

I have written some classes and modules which I can include in my ruby scripts using require/require_relative.

What we should include our scripts; classes or modules ? Does one has some benefit(s) over another ?

Forgive my ignorance on this topic. May be this question is stupid. I just wanted to progress my work in the right direction. Thanks in advance for your comments/suggestions.

vikas027
  • 5,282
  • 4
  • 39
  • 51
  • have you read this? http://stackoverflow.com/questions/3672586/what-is-the-difference-between-require-relative-and-require-in-ruby – emi Jan 13 '15 at 00:25
  • @siaw23 I went through the link. May be I was not clear, sorry about that.. I am not asking 'how' to include module/classes but 'what' to include as per general or best practices. Should I write modules or classes (with methods) to be in included in my scripts. – vikas027 Jan 13 '15 at 01:13

2 Answers2

2

Modules and classes have a lot in common. Modules as you probably may know can't be instatiated but classes can. So what's the best use for modules and when do you use them? Well, the simplest answer would be if you have more than one class that share common methods. The best practice and wisest thing to do is to write a module that includes these common methods between the classes and include the module in these classes where you want to use these "common methods". Otherwise if you have just one class then it doesn't make much sense creating a module for the class. You could as well create these methods in the class itself and forget completely about the module. Unless of course you have similar methods that you want to group them into modules just for the sake of organization and keeping your code minimal and for refactoring later (when the need arrives).

The same for classes. You can require your classes if you have lots of different classes that you have organized into your scripts. This again, makes more sense if you have a lot of classes.

I hope this answered your question.

emi
  • 2,830
  • 5
  • 31
  • 53
1

I would suggest to use require_relative to use any scripts that may not be available in load_path. Hence use it for all scripts that are specific to your current working directory. require on the other hand tends to look in the load_pathand it may load an available gem of the same name if you have given a clashing name for the file. So, I would suggest to always use require_relative for specific files/directories in the project.

EDIT:

Modules or Classes: In my opinion Modules are better than classes as Classes are actually Modules under the covers. And moreover Modules are most common for such requirements.

Jikku Jose
  • 18,306
  • 11
  • 41
  • 61
  • I am not asking 'how' to include module/classes but 'what' to include as per general or best practices. Should I write modules OR classes (with methods) to be in included in my scripts ? – vikas027 Jan 13 '15 at 02:40