-1

How can I call an application controller method inside of a Ruby file? I can't use the traditional MVC architecture.

Thanks!

user3245240
  • 265
  • 4
  • 10
  • 1
    You mean you have a Rails application which has a method in the ApplicationController and you want to call a method on that class from a ruby file in the project but not part of the request cycle? Please clarify the question. – Leo Correa Jan 12 '15 at 17:58
  • Could you show us your ApplicationController, describe what the method in question does, and the context in which the other ruby file is being ran? – Kyle Decot Jan 12 '15 at 18:00

3 Answers3

0

If the method is meant to be called from both the application controller and some other ruby file, then you need to move that method to another file, probably a Plain Old Ruby Object (PORO). Then, require that file from your controller and from whatever other file needs to use it.

It's a good idea to only have controller-related logic in controllers. Since you're calling this method from something besides a controller, it must not be strictly controller-related logic, so this is the perfect opportunity to move it.

sockmonk
  • 4,195
  • 24
  • 40
0

If you have a method in the ApplicationController and you need to call it you can use a trick which is:

ApplicationController.new.#method_here

But you better move the method to a plugin and call it in the ApplicationController for a best practice.

More info here:

How do I call controller/view methods from the console in Rails?

https://stackoverflow.com/a/9159853/2552259

Community
  • 1
  • 1
Jorge de los Santos
  • 4,583
  • 1
  • 17
  • 35
0

The best approach for your problem is to extract the method in question and put it in a module, like lib/my_utils.rb. Then you can require this file where ever you need it:

# lib/my_utils.rb
module MyUtils
  def the_method_you_were_talking_about(args)
    .. code ..
  end
end

Then:

# application_controller.rb
require 'lib/my_utils.rb'
MyUtils.the_method_you_were_talking_about("and any data you need to pass to it")

And then you'd do the same thing from your other ruby file.

DiegoSalazar
  • 13,361
  • 2
  • 38
  • 55