Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How not to write full module path in ruby?

Tags:

ruby

Lets consider I have a class inside a really long module path:

sux = Really::Long::Module::Path::Sucks.new

Could I somehow "import" this module in a way that I could just use the class without worrying writing this path every time I use it?

EDIT: I know being in the same module makes things easier. But I can't be in the same module in this case.

like image 619
Victor Rodrigues Avatar asked Feb 08 '11 23:02

Victor Rodrigues


People also ask

What does __ FILE __ mean in Ruby?

The value of __FILE__ is a relative path that is created and stored (but never updated) when your file is loaded. This means that if you have any calls to Dir.

How do you create a module in Ruby?

Creating Modules in Ruby To define a module, use the module keyword, give it a name and then finish with an end . The module name follows the same rules as class names. The name is a constant and should start with a capital letter. If the module is two words it should be camel case (e.g MyModule).

Can a module contain a class Ruby?

A Ruby module can contain classes and other modules, which means you can use it as a namespace.

How do you call a module method in Ruby?

As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.


2 Answers

Modules are an object in ruby, so you can just make a reference to the module that is shorter.

Sux = Really::Long::Module::Path::Sucks
Sux.new
like image 119
cam Avatar answered Sep 17 '22 20:09

cam


In your class:

include Really::Long::Module::Path

This basically mixes all of that module's constants/methods into the including class, so you can then use the Sucks class directly:

sux = Sucks.new
like image 40
Chris Heald Avatar answered Sep 20 '22 20:09

Chris Heald