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

混江龙づ霸主 提交于 2019-12-06 03:51:13

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!