重新定义 Rails 的方法 [英] Redefining Rails' methods

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

问题描述

Rails 方法 Array#to_sentence 允许以下内容:

The Rails method Array#to_sentence allows for the following:

['a', 'b', 'c'].to_sentence # gives: "a, b, and c"

我想扩展此方法以允许它接受一个块,以便您可以执行以下操作(其中 people 是 Person 对象的数组,具有 name 属性):

I would like to extend this method to allow it to take a block, so that you can do something like the following (where people is an array of Person objects, which have the name attribute):

people.to_sentence { |person| person.name }
# => "Bill, John, and Mark"

我写扩展方法没有问题.但我不知道把它放在哪里.Rails 核心扩展被加载到 ActiveSupport 深处的某个地方.我需要一个地方,用户定义的代码总是被加载,并且是预加载的(在任何应用程序代码之前).

I don't have a problem with writing the extension method. But I can't work out where to put it. The Rails core extensions get loaded somewhere down in the depths of ActiveSupport. My need is for a place where user-defined code is always loaded, and is pre-loaded (before any application code).

推荐答案

创建 config/initializers/super_to_sentence.rb.此目录中的所有文件都在 Rails 加载后加载,因此您将有机会覆盖 Rails 对 Array#to_sentence 的定义.

Create config/initializers/super_to_sentence.rb. All files in this directory are loaded after Rails has been loaded, so you'll have a chance to override Rails' definition of Array#to_sentence.

对于要在 Rails 加载之前加载的代码,请将其添加到 config/environment.rb.

For code you want to load before Rails gets loaded, add it to config/environment.rb.

这篇关于重新定义 Rails 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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