如何在不使用全局变量的情况下使用Logger而不是put

时间:2014-04-17 09:25:42

标签: ruby

我开始使用PullReview进行Ruby练习。它给出以下错误。

Use a logger instead of puts or add assertion.

require_relative '../lib/soshisoai'

file_path = File.expand_path('../../spec/fixtures/soshisoai3.txt', __FILE__)

myarr1 = Soshisoai.parse_file(file_path)
myarr2 = Soshisoai.get_combi(myarr1)
myarr3 = Soshisoai.flat_arr(myarr2)
myarr4 = Soshisoai.eliminate_duplicate(myarr3)
myarr5 = Soshisoai.swap_male(myarr4)
myarr6 = Soshisoai.find_match(myarr5)
myarr7 = Soshisoai.delete_same_suffix(myarr6)
myarr8 = Soshisoai.delete_same_prefix(myarr7)
puts myarr8

Why

You don't want to clutter your logs with raw puts, pp, or p. Output using p 
will not always appear in your logs, nor will it inherit from any log config 
you may have (to add information such as the timestamp).

How to fix

In a Rails application
Use Rails.logger instead.

In Ruby code
Just use the Logger class.

In unit and integration tests
This is often a sign that you are missing some asserts and other checks.

然后,我使用了Logger,但它又出现了另一个错误。

Avoid global variable.

require_relative '../lib/soshisoai'
require 'logger'

$Log = Logger.new('log_file.log')
$Log.debug('Soshisoai3')
file_path = File.expand_path('../../spec/fixtures/soshisoai3.txt', __FILE__)

myarr1 = Soshisoai.parse_file(file_path)
myarr2 = Soshisoai.get_combi(myarr1)
myarr3 = Soshisoai.flat_arr(myarr2)
myarr4 = Soshisoai.eliminate_duplicate(myarr3)
myarr5 = Soshisoai.swap_male(myarr4)
myarr6 = Soshisoai.find_match(myarr5)
myarr7 = Soshisoai.delete_same_suffix(myarr6)
myarr8 = Soshisoai.delete_same_prefix(myarr7)
$Log.debug(myarr8)

Why

This check reports global variables. Global variables introduce strong dependencies 
between otherwise unrelated parts of code and their usage is usually considered 
extremely bad style.

How to fix

If you need a variable in many different places, here are some options other 
than using a global
...

如何避免这些错误?

2 个答案:

答案 0 :(得分:2)

就像Rails.logger那样:让它成为你的一个类的实例变量(假设你使用Rails,否则你也可以使用{{1}本身)。确保使用的实例变量而不是对象的实例变量。从技术上讲,这几乎是一个全局变量,但它应该足以避免Rails.logger的抱怨。像

这样的东西
PullReview

应该允许您在没有投诉的情况下致电require 'logger' class MyApp @logger=Logger.new("/tmp/log") def self.logger @logger end end ,当然您可以自由使用您想要的任何日志记录类。

答案 1 :(得分:0)

如何使用实例变量

@log = Logger.new('log_file.log')

然后你可以在同一个对象中使用@log。