Railsでバッチ処理を作成してみる(runnerの場合)

RailsでSQLを確認してみる
の続き

Railsで、runnerを使って、バッチ処理を作成してみる。

作成

今回はlibの下に作成する。

$ vi lib/sample.rb
class Sample
  def self.hello
    puts "hello world"
  end
end

libへのパスを設定する。

$ vi config/application.rb
module SampleMysql
  class Application < Rails::Application
    ・・・
    config.autoload_paths += %W(#{config.root}/lib)	 ←追加
  end
end

実行すると、「hello world」が出力される。

$ rails runner Sample.hello
hello world

モデルの読み込み

Userモデルの検索結果を出力するよう修正する。

$ cat lib/sample.rb
class Sample
  def self.hello
    puts User.first().to_yaml
  end
end

実行すると、検索結果が出力される。

$ rails runner Sample.hello
--- !ruby/object:User
attributes:
  id: 1
  name: 佐藤
  point: 100
  flag: true
  day: 2001-01-01
  created_at: 2014-01-12 07:09:56.000000000 Z
  updated_at: 2014-01-12 07:09:56.000000000 Z

ログの出力

ログを出力するには、Loggerをnewする必要がある。

$ vi lib/sample.rb
class Sample
  def self.hello
    logger = Logger.new('log/development.log')
    logger.debug(User.first().to_yaml)
  end
end

実行すると、ログが出力される。

$ rails runner Sample.hello
$ cat log/development.log
D, [2014-08-04T17:15:16.219680 #1544] DEBUG -- : --- !ruby/object:User
attributes:
  id: 1
  name: 佐藤
  point: 100
  flag: true
  day: 2001-01-01
  created_at: 2014-01-12 07:09:56.000000000 Z
  updated_at: 2014-01-12 07:09:56.000000000 Z

モジュールの読み込み

モジュールを作成する。

$ vi app/controllers/concerns/module_test.rb
module ModuleTest
  def hoge
    puts "hello world from module"
  end
end

モジュールを呼び出すよう修正する。
※モジュールは自動で読み込まれず、includeが必要。

$ vi lib/sample.rb
include ModuleTest

class Sample
  def self.hello
    hoge
  end
end

実行すると、モジュールのメソッドが実行される。

$ rails runner Sample.hello
hello world from module