How to call controller's method

2019-08-22 21:05发布

问题:

I have a functionality that doesn't relate to incoming requests (like get,post,etc).

But I want to follow MVC convention and make it like Model-Controller:

  • in controller part I will process income requests from another parts, decide from which model it should retrieve information, authorization, filtering and so on;

  • in model part I will store information, validate it, expire it and etc.

In Rails the controller's actions can be called by income request directed by routes file.

The problem for me that if I've created a controller like this:

class SomeController < ApplicationController

  def some_action; end

end

How can I call method some_action from SomeController from any place in my application?

P.S. Calling SomeController.new.some_action doesn't seem right to me, because I think all controllers are parts of app object.

回答1:

You can do this by instanciating the controller.

SomeController.new.some_action

However this is not really an MVC way. I don't really know what you want to use it for, but probably there is a better way. For example it can be done as in the model, as the modification of data should belong there not to a controller.



回答2:

I think you should probably create a PORO which will encapsulate this functionality in some method. So that any logic dependent functionality should be within that instead of in the controller. Then you can call them in either controller.