本文介绍了在 Rails 中,如何向 String 类添加新方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的 Rails 项目中的不同对象建立一个索引,并想添加一个我可以在 String 对象上调用的count_occurences"方法.

I want to build an index for different objects in my Rails project and would like to add a 'count_occurences' method that I can call on String objects.

我发现我可以做类似的事情

I saw I could do something like

class String
  def self.count_occurences
    do_something_here
  end
end

定义此方法的确切方法是什么,以及将代码放在我的 Rails 项目中的什么位置?

What's the exact way to define this method, and where to put the code in my Rails project?

谢谢

推荐答案

您可以在您的应用程序中定义一个新类 lib/ext/string.rb 并将此内容放入其中:>

You can define a new class in your application at lib/ext/string.rb and put this content in it:

class String
  def to_magic
    "magic"
  end
end

要加载此类,您需要在 config/application.rb 文件或初始化程序中要求它.如果你有很多这样的扩展,初始化程序会更好!加载方式很简单:

To load this class, you will need to require it in your config/application.rb file or in an initializer. If you had many of these extensions, an initializer is better! The way to load it is simple:

require 'ext/string'

to_magic 方法将在您的应用程序/控制台内的 String 类的实例上可用,即:

The to_magic method will then be available on instances of the String class inside your application / console, i.e.:

>> "not magic".to_magic
=> "magic"

无需插件.

这篇关于在 Rails 中,如何向 String 类添加新方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 03:15