How can I call an application controller method inside of a Ruby file? I can't use the traditional MVC architecture.
Thanks!
How can I call an application controller method inside of a Ruby file? I can't use the traditional MVC architecture.
Thanks!
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.
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?
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.