在哪里放置在多个模型中找到的通用代码? [英] Where to put common code found in multiple models?

查看:71
本文介绍了在哪里放置在多个模型中找到的通用代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个包含相同方法的模型:

I have two models that contain the same method:

def foo
  # do something
end

我应该把它放在哪里?

我知道通用代码位于Rails应用程序的 lib目录中.

I know common code goes in the lib directory in a Rails app.

但是,如果我将它放在lib中名为"Foo"的新类中,并且需要将其功能添加到我的两个ActiveRecord models中,我是否应该这样做?

But if I put it in a new class in lib called 'Foo', and I need to add its functionality to both of my ActiveRecord models, do I do that like this:

class A < ActiveRecord::Base
includes Foo

class B < ActiveRecord::Base
includes Foo

,然后AB都将包含foo方法,就像我在每个方法中都定义了一样?

and then both A and B will contain the foo method just as if I had defined it in each?

推荐答案

创建一个模块,您可以将其放在lib目录中:

Create a module, which you can put in the lib directory:

module Foo
  def foo
    # do something
  end
end

然后您可以include每个模型类中的模块:

You can then include the module in each of your model classes:

class A < ActiveRecord::Base
  include Foo
end

class B < ActiveRecord::Base
  include Foo
end

AB模型现在将定义foo方法.

The A and B models will now have a foo method defined.

如果使用模块名称和文件名称(例如foo.rb中的Foo和foo_bar.rb中的FooBar)遵循Rails命名约定,则Rails会自动为您加载文件.否则,您将需要使用require_dependency 'file_name'加载您的lib文件.

If you follow Rails naming conventions with the name of the module and the name of the file (e.g. Foo in foo.rb and FooBar in foo_bar.rb), then Rails will automatically load the file for you. Otherwise, you will need to use require_dependency 'file_name' to load your lib file.

这篇关于在哪里放置在多个模型中找到的通用代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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