模型“实用程序"放在哪里Ruby on Rails 中的函数 [英] Where to put model "utility" functions in Ruby on Rails

查看:26
本文介绍了模型“实用程序"放在哪里Ruby on Rails 中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个模型的 Rails 应用.

I have a rails app with several models.

我想从多个模型访问一个函数.

I have a function that I want to access from several models.

放置此代码的最佳位置是什么,我如何使其可从需要获取它的模型中访问?

What's the best place to put this code and how can I make it accessible from the models that need to get at it?

我的理解是助手仅用于视图.这是正确的吗?

My understanding is that helpers are just for views. Is this correct?

创建插件并将其放在供应商文件夹中似乎是错误的 - 这是我的代码并且是我的应用程序不可或缺的一部分.这是正确的吗?

It seems wrong to create a plug-in and put it in the vendor folder - this is my code and integral to my app. Is this correct?

谢谢.

推荐答案

最简单的解决方案是在 lib 下创建一个模块并将其混合到需要它的模型中,例如,在 lib/fooable.rb 中:

The simplest solution would be to create a module under lib and mix this into the models that need it, for instance, in lib/fooable.rb:

module Fooable
  def do_foo
  end
end

然后在您的各种模型中:

And then in your various models:

class MyModel < ActiveRecord::Base
  include Fooable
end

不需要 fooable.rb,只要使用正确的约定命名,Rails 自动加载机制就会为您找到它.

No need to require fooable.rb, the Rails autoloading mechanism will find it for you as long as it's named using correct conventions.

这篇关于模型“实用程序"放在哪里Ruby on Rails 中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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