Colin Wu
Colin Wu

Reputation: 699

Is it possible to run a Rails controller method with runner?

Suppose I have a Rails 4 application that keeps track of usage counters in a piece of equipment, so my controller has a method, record_usage, that can be interactively invoked from a view to immediately retrieve and record the usage counter. But, I also want to run the same method periodically, so I extract the code into a stand-alone .rb file and run it periodically via cron with

rails r -e production record_usage.rb

My question is: in the interest of "DRY" can I invoke the controller method directly from within 'record_usage.rb', rather than maintaining a separate copy of the record_usage code in the .rb file?

Upvotes: 0

Views: 592

Answers (1)

max
max

Reputation: 102055

You don't invoke controller methods externally unless you want seven years of bad luck and the wrath of the MVC gods!

The public API of a controller is the actions that respond to HTTP requests. EVERYTHING else should be a private method.

Remember that the role of a controller in MVC is a class that takes a request and returns a response. Thus its not the place to shove all those little utilities.

In fact if you want to call something externally from your controller that is very strong signal that your controller is fat and that you should refactor by moving business logic into the model layer.

Aslo using single purpose objects known as service objects is a good way to clean up controllers that coincidentally lends itself very well to rake tasks and unit testing:

module CleanupService
  def self.call(foo)
    foo.dot_the_is
    foo.cross_the_ts 
  end
end

Not everything in MVC has to be a model, view or controller. Thats just the backbone.

Upvotes: 3

Related Questions