13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Railsでは、rails runnerコマンドでRubyファイルを直接実行できるらしい。

基本的にはこのサイトを参考にした

1. libディレクトリのファイルへのパスの設定

以下の設定をconfig/application.rbに追加。

application.rb
config.autoload_paths += %W(#{config.root}/lib)

2. rails runnerコマンドで実行するプログラムの作成

libの下に以下の内容でファイルを作成

get_rss.rb
class Cron::GetRss
  def self.get_rss
    # 実行したい処理
  end
end

参考にしたサイトではlib/tasksにファイルを作成していたが、lib以下ならどこでもいいらしい。
lib/tasksには、独自のRakeタスクのみ置いた方がわかりやすいと思った。

なので、今回はlib/cron/get_rss.rbを作成。
クラス名を上記のようにCron::GetRssにしないとrails runnerでエラーが起こる。
たとえば、lib/pdf_stuff/receipt.rbなら、クラス名はPdfStuff::Receiptにする。

この辺の情報が役に立った

  • RailsによるアジャイルWebアプリケーション開発 第4版 245ページ

3. 実行

ターミナルでrails runnerコマンドを実行。
rails runner Cron::GetRss.get_rss

13
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?