向 Rails 应用程序中的内置类添加方法 [英] adding a method to built-in class in rails app

查看:33
本文介绍了向 Rails 应用程序中的内置类添加方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想向 Rails 应用程序中的 Array 类添加一个方法.我应该把这个方法放在哪里?

I want to add a method to the Array class in a rails app. Where should I put this method?

编辑更清楚,显然我把它放在某个文件中,但我如何告诉 rails 应用程序在哪里可以找到它?

EDIT to be clearer, obviously I put it in a file somewhere, but how do I tell the rails app about where to find it?

推荐答案

一种方法是在 lib/rails_extensions.rb 中创建一个文件.然后,像这样添加你的扩展:

One way to do this is to create a file at lib/rails_extensions.rb. Then, add your extensions like so:

class Array
  def bring_me_food
    # ...
  end

  def make_tea
    # ...
  end
end

class Hash
  def rub_my_shoulders
    # ...
  end
end

然后在 config/environment.rb 中添加:

require 'rails_extensions'

您与从属对象的距离可能会有所不同.

Your mileage with subservient objects may vary.

这篇关于向 Rails 应用程序中的内置类添加方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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