shin
shin

Reputation: 32721

How to use Logger instead of puts in Ruby without using global variable

I started using PullReview for my Ruby practice. It gives the following error.

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.

Then, I used Logger, but it gave another error.

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
...

How can I avoid these errors?

Upvotes: 2

Views: 1626

Answers (2)

Patru
Patru

Reputation: 4551

Just do as the Rails.logger does: make it an instance variable of one of your classes (assuming you are not using Rails as otherwise you might just as well use Rails.logger itself). Make sure to use an instance variable of the class and not of an object though. Technically this is almost a global variable, but it should be enough to avoid the complaints of PullReview. Something like

require 'logger'

class MyApp
  @logger=Logger.new("/tmp/log")
  def self.logger
    @logger
  end
end

should allow you to call MyApp.logger without complaints and of course you will be free to use whatever logging class you desire.

Upvotes: 2

user3530367
user3530367

Reputation: 21

how about using instance variable

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

Then you can use @log within the same object.

Upvotes: 0

Related Questions