Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method visible everywhere in Rails

How can I make this method, which outputs a yellow line in the log file, accessible from everywhere (Models, Controllers, Views) in my Rails app?

def my_log(text, file = "", line = "")
  text.to_s.chomp.gsub!(/%/, "%%")
  Rails.logger.debug(sprintf("\033[32m#{file}#{line}\033[0m\033[1m\033[33m#{text}\033[0m"))
end
like image 505
Lucamug Avatar asked Nov 29 '22 16:11

Lucamug


2 Answers

You could define it in Kernel (NOT recommended):

module Kernel
  def my_log(..)
    ..
  end
end

... if you really want it available anywhere.

Or, place something like this in lib/util.rb:

module Util
  def self.my_log(..)
    ..
  end
end

... and make sure to require 'util' in your config/application.rb and then you can call this anywhere:

Util.my_log(..)
like image 184
Jits Avatar answered Dec 07 '22 00:12

Jits


why not create an initializer and write this method to the rails module?

# config/initializers.rb
module Rails

  def self.log_with_colour(message, level = :debug)
    text.to_s.chomp.gsub!(/%/, "%%")
    logger.send(level, sprintf("\033[32m#{__FILE__}#{__LINE__}\033[0m\033[1m\033[33m#{message}\033[0m"))
  end

end

in your code you can then call Rails.log_with_colour("hello") or Rails.log_with_colour("Hello again", :info)

like image 35
bodacious Avatar answered Dec 06 '22 23:12

bodacious