Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Whenever Gem How to Run Specific Method in Controller.rb File

I am looking to run a specific method inside my controller.rb file every minute. I am looking at using the whenever gem for rails but I am a bit confused on how to do this.

Currently in schedule.rb I have:

every 1.minutes do 
runner "Server.update_all_servers"
end

I am unsure exactly what the runner command does. Could someone explain what this command exactly does? From my understanding it calls a Model.ModelMethod but I need to call a method in application_controller.rb called update_all_servers(). Is it possible to do this? Or would I have to move whatever is inside my application_controller.rb to a model file (such as the one located in /models/server.rb)?

like image 463
Rahul Avatar asked Sep 17 '25 05:09

Rahul


2 Answers

You can create a Server class in /lib:

class ServerUpdater
    attr_accessor :servers

    def initialize(servers = nil)
        @servers = servers || Server.all
    end

    def update_all
        servers.find_each { |server| server.update_info }
    end
end

Then you can call ServerUpdater.new(@servers).update_all in your controller.

In your cron job, you would call ServerUpdater.new(Server.all).update_all

And you would need an update_info method in your model that would contain the logic.

like image 70
Robin Avatar answered Sep 19 '25 07:09

Robin


I had the same question and I solved it straight forward and didn't have to add anything in lib so I wanted to share:

In your case you want to call a controller action, all you do is have all your logic in the model method and that's best practice anyway. The runner can then simply call the model method:

every 1.minutes do 
  runner "Server.update_all_servers"
end

Server.update_all_servers has to be a method in your Server model and not a controller action.

like image 39
Maher Manoubi Avatar answered Sep 19 '25 06:09

Maher Manoubi