Search code examples
ruby-on-railsrubyirb

How do I prevent output ActiveRecord::Base.logger from within a method?


The method below takes a few minutes to print out the database entry each time I call it in the console. I need to see the printing the rest of the time so shutting it off entirely isn't an option.

This is my unsuccessful attempt to stop the printing in the method directly.

def generate_dataset
  old_logger = ActiveRecord::Base.logger
  ActiveRecord::Base.logger = nil

  ProductDatum.create(product_names: Products.all.pluck(:name))

  ActiveRecord::Base.logger = old_logger
end


Solution

  • You're looking for #silence, which takes a block during which the logger is silenced:

    def generate_dataset
      ActiveRecord::Base.logger.silence do
        ProductDatum.create(product_names: Products.all.pluck(:name))
      end
    end