RailsでModelやController以外からloggerを使用する

共通処理をモジュールなどにまとめる場合、そのモジュールないの logger.debug ... と普通に記述していることが多いと思います。ところが、このモジュールをテストしようとするとエラーになります。

[sourcecode language="bash"] NameError: undefined local variable or method logger' for test_add_item_to_hash_param_is_nil(ConditionUtilTest):ConditionUtilTest lib/condition_util.rb:36:inadd_item_to_hash' test/unit/condition_util_test.rb:33:in `block in <class:ConditionUtilTest>'

1 tests, 3 assertions, 0 failures, 1 errors, 0 pendings, 0 omissions, 0 notifications [/sourcecode]

該当する行には次の通りloggerメソッドが使用されていました。

[sourcecode language="ruby"] def add_item_to_hash(hash, key, value, range_to = nil)

...

if range_to.nil?
  if !key.nil? &amp;&amp; !value.to_s.empty
    if !hash.key? key
      hash[key] = value
      # ここでエラーになっている
      logger.debug &quot;the hash add item. key:&quot; + key.to_s + &quot; / value:&quot; + hash[key].to_s
    end
  end
else
  ...
end

end [/sourcecode]

この場合に、次の通りにすればModelやController以外からloggerメソッドを使用できるようになります。

[sourcecode language="ruby"] def add_item_to_hash(hash, key, value, range_to = nil)

...

if range_to.nil?
  if !key.nil? &amp;&amp; !value.to_s.empty
    if !hash.key? key
      hash[key] = value
      # Rails.logger.…を使用すればOK
      Rails.logger.debug &quot;the hash add item. key:&quot; + key.to_s + &quot; / value:&quot; + hash[key].to_s
    end
  end
else
  ...
end

end [/sourcecode]

とりあえず、一つ解決です。

ちなみに、参考にしたのはこちらのサイトです。

Using the Rails logger outside of models and controllers  - Jason Seifer