在Rails中随处可见的方法 [英] Method visible everywhere in Rails

查看:54
本文介绍了在Rails中随处可见的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使该方法在日志文件中输出一条黄线,并且可以在我的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

推荐答案

您可以在Kernel中定义它(不推荐):

You could define it in Kernel (NOT recommended):

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

...如果您真的希望它在任何地方都可用.

... if you really want it available anywhere.

或者,将这样的内容放入lib/util.rb:

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

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

...,并确保在config/application.rb中输入require 'util',然后可以在任何地方调用此名称:

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

Util.my_log(..)

这篇关于在Rails中随处可见的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆