Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute a method in a module from the Rails console?

I have a module in a file called my_mod.rb declared like this:

module Reports   module MyMod      def mymethod       ...     end    end end 

I just want to run mymethod. It's not a class method obviously, so I can't run it like:

Reports::MyMod.mymethod 

and yet I was hoping there was some way to get the method evaluated by the parser without have to go through a bunch of module_eval and module_function stuff. It should be easier than that, shouldn't it?

like image 464
AKWF Avatar asked Oct 17 '12 14:10

AKWF


People also ask

How do you call a method in a module?

The method definitions look similar, too: Module methods are defined just like class methods. 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.

How do you access a module method in Ruby?

A user cannot access instance method directly with the use of the dot operator as he cannot make the instance of the module. To access the instance method defined inside the module, the user has to include the module inside a class and then use the class instance to access that method.

What is the Rails console?

Rails console is a command line program for interacting with the Rails applications. It has the full power of the Ruby language and Rails environment.

How to Start the Rails console?

Go to your browser and open http://localhost:3000, you will see a basic Rails app running. You can also use the alias "s" to start the server: bin/rails s . The server can be run on a different port using the -p option. The default development environment can be changed using -e .


1 Answers

To run it from the rails console you just have to include it:

> include Reports::MyMod > mymethod 
like image 158
Lucca Mordente Avatar answered Sep 22 '22 09:09

Lucca Mordente