/ rails

Creating a module and autoloading it in Rails 5

So I tried to create a module and to autoload it in Rails 5.

Module: /lib/debug_log.rb

module DebugLog
  def self.log (msg = nil, file = nil)
    file = "#{Rails.root}/log/debuglog.log" if file.nil?
    logger = Logger.new(file)

    logger.debug(msg) unless msg.nil?
  end

  def self.clean ()
    file = "#{Rails.root}/log/debuglog.log" if file.nil?
    File.open(file, 'w') { |file| file.truncate(0) }
  end
end

The purpose of this module is to easily output strings to a log file. Mainly for use in the console.

And to autoload it, so you don't have to call require 'DebugLog' add the following to /config/application.rb

module Myapp
  class Application < Rails::Application
    # Autoload files in /lib
    config.autoload_paths += %W( lib/ )
  end
end

With this, you can simply do DebugLog.log 'some string' in the console, to log the string to /log/debuglog.log.

Creating a module and autoloading it in Rails 5
Share this