-1

I'm trying to add the function that is defined in the controller.rb file to the rake file. The Name of this controller file is "home_controller.rb". Here I put a part of the code.

class HomeController < ApplicationController
def rclass_creation
    #output = "rclass is created"
    a = Rclass.all
    a.destroy_all...

I made my_namespace.rake file under tasks in the lib folder. Here I put the code a bit.

namespace :my_namespace do
  desc "TODO"
  task my_task2: :environment do

  a = Userpool.all
  a.each do |user|
  puts user.name
  end
  puts "wow it is working"

I was able to call the database. I think this is because the rake file has an access to the database ( Userpool ). In this rake file, I want to call the function "rclass_creation" that was stated in the "home_controller.rb" because I want to avoid the situation that I have to do hardcopy.

The sudo code might look like this ( I hope (: )

namespace :my_namespace do
  desc "TODO"
  task my_task2: :environment do

  status = rclass_creation <= from home_controller.rb
  a = Userpool.all
  a.each do |user|
  puts user.name
  end
  puts "wow it is working"

The function I want to call is "rclass_creation" from the home_controller. How can I call the function from the controller to rake file ? I'm looking forward to seeing opinions from the experts!!

Sungpah Lee
  • 1,003
  • 1
  • 13
  • 31
  • possible duplicate of [Call controller from rake task](http://stackoverflow.com/questions/22936245/call-controller-from-rake-task) – Brad Werth Jul 12 '15 at 03:36

1 Answers1

1

You don't call controller methods from anywhere but the controller.

If you want to use a controller action from a rake file you should invoke it with a HTTP request. Just like any client would do.

You can initialize a controller and call methods on it but that's really hacky. Don't.

If you need to share code between your rake task and controller than it should not be in a controller at all.

So where do you put the code?

  • Does it act on a model? Is it independent from application state? Does it belong in a model? Put in a your model.
  • Is a mixin? Or just a plain method with takes some input and shoots something out? Put in into a helper or a plain old module.
  • Is it some kind of service that takes input and does something with models? Put it in a service object.
Community
  • 1
  • 1
max
  • 96,212
  • 14
  • 104
  • 165
  • The reason why you do this is that you don't want your controllers to end up being the junk drawer of your application - keep them skinny. The only public methods in your controller should be the actions that correspond to a route. – max Jul 12 '15 at 02:35