[英]Where should I place my own “module” within rails application?
Some functionality within my rails application looks better as if it was a separate "module", that should be accessed via require
. 我的rails应用程序中的某些功能看起来更好,就好像它是一个单独的“模块”,应该通过require
访问。 For example, assume it's a function to calculate Fibonacci numbers. 例如,假设它是计算斐波纳契数的函数。
The functionality is independent on rails application and can be reused in other projects, so it should not be stored near application controllers and models, I suppose. 该功能独立于rails应用程序,可以在其他项目中重用,因此我不应该将它存储在应用程序控制器和模型附近。 But since I'm not going to detach it into separate project, thus placing it to vendor
folder seems like not the right thing. 但是因为我不打算将它分离到单独的项目中,所以把它放到vendor
文件夹似乎不是正确的事情。
Where should I place it then? 我应该把它放在哪里?
The place to put reusable code such as this is in the lib
directory. 放置可重用代码的地方就在lib
目录中。 However you do not need to require
anything as lib
is already in the load path and it's contents will be loaded during initialization. 但是,您require
任何内容,因为lib
已经在加载路径中,并且它的内容将在初始化期间加载。
If you need to extend an existing class, you define your module first and then include it by sending it as a message to the class you wish to extend, eg 如果需要扩展现有类,首先定义模块,然后通过将其作为消息发送到要扩展的类来包含它,例如
module MyExtensions
def self.included base
base.instance_eval do
def my_new_method
…
end
end
end
end
ActiveRecord::Base.send :include, MyExtensions
I'll often put stuff in lib
, it turns out that anything under lib is in the load path and doesn't need to be require
d at all. 我经常把东西放在lib
,事实证明lib下的任何东西都在加载路径中,根本require
d。
edit: After Steve's comment, removed the bit about having to require the files. 编辑:在史蒂夫的评论之后,删除了关于不得不要求文件的一点。 Also, removed a couple requires from some of my code :P 另外,从我的一些代码中删除了一对夫妇:P
There is a lib directory in RoR projects which fits well for that purpose - I place common bits of code in form of "libraries" there. RoR项目中有一个lib目录,非常适合这个目的 - 我在那里以“库”的形式放置了常见的代码。 Anything from extending ActiveRecord classes to reusable utility methods. 从将ActiveRecord类扩展到可重用的实用程序方法的任何东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.