3

for example I have a controller "Posts" and action "create". Can I run it from terminal?

I want to use whenever gem:

every 2.hours do
    # I want to run posts#index
end

How can I do it?

  • Why do you want to call your controller action from cron? Wouldn't be better if you only run what should be done, for example rake task that creates `Post`? – Marek Lipka Feb 10 '15 at 10:20
  • I want to run it every 2 hours. How can I do it then? @MarekLipka –  Feb 10 '15 at 10:26
  • I know you want to run it every 2 hours. The question was *why* do you want to call it every 2 hours? Write your rake task that would make request to proper address (with `Net::HTTP` for example) and it should work. – Marek Lipka Feb 10 '15 at 10:29
  • Like @MarekLipka said, while your app is running, locally or in a remote server, you can use any http client like [rest_client](https://github.com/rest-client/rest-client) to post data to your application. – Nafaa Boutefer Feb 10 '15 at 10:34

1 Answers1

5

One solution is create a class that execute the create logic:

class PostsController < ApplicationController

  def create
    creator = PostCreator.new(params)
    creator.process
  end
end

So you can use this class in the Whataver's job:

every 2.hours do
  creator = PostCreator.new({ whatever: 'you want'})
  creator.process
end
Rodrigo
  • 5,435
  • 5
  • 42
  • 78