Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking ruby module across several files

I have a ruby module that is supposed to wrap up quite a few classes

module A   class First     #somemethods   end    class Second     #somemethods   end    class Third     #somemethods   end end 

What i would like to do in rails is to break up these classes into several files what might be the best practice to split this huge module into several relevant files?

like image 396
Kapil Avatar asked Aug 20 '12 09:08

Kapil


People also ask

What is a Ruby mixin?

Mixins in Ruby allows modules to access instance methods of another one using include method. Mixins provides a controlled way of adding functionality to classes. The code in the mixin starts to interact with code in the class. In Ruby, a code wrapped up in a module is called mixins that a class can include or extend.

Can a Ruby module be inherited?

The Ruby class Class inherits from Module and adds things like instantiation, properties, etc – all things you would normally think a class would have. Because Module is literally an ancestor of Class , this means Modules can be treated like classes in some ways. As mentioned, you can find Module in the array Class.

How do I use a class from another file in Ruby?

To put a class in a separate file, just define the class as usual and then in the file where you wish to use the class, simply put require 'name_of_file_with_class' at the top.

What is the difference between a class and a module Ruby?

What is the difference between a class and a module? Modules are collections of methods and constants. They cannot generate instances. Classes may generate instances (objects), and have per-instance state (instance variables).


1 Answers

One approach would be to come up with directory structure like this:

(root dir) ├── a │   ├── first.rb │   ├── second.rb │   └── third.rb └── a.rb 

Files contents:

# a.rb require_relative './a/first.rb' require_relative './a/second.rb' require_relative './a/third.rb'  module A end   # a/first.rb module A   class First     # ...   end end   # a/second.rb module A   class Second     # ...   end end   # a/third.rb module A   class Third     # ...   end end 
like image 103
Victor Deryagin Avatar answered Oct 14 '22 01:10

Victor Deryagin