问题描述
关于lib目录的问题.
Question about lib directory.
使用 lib 目录有哪些好的做法?
什么时候应该在应用程序/模型或应用程序/助手上使用它?
与如何让 Rails 3 包含 lib 目录中的文件有些相关?
What are good practices in using the lib directory?
When should it be used over app/models or app/helpers?
And somewhat related how do you get Rails 3 to include files from the lib directory?
谢谢
推荐答案
lib 目录的一个用途(我最常使用它的方式)是在模型之间共享代码以保持 DRY.例如,如果您要在许多不同模型上定义 tag_tokens
属性以与标记器输入一起使用,您可以将其放在tag_accessor.rb"或其他内容中,将其放在 /lib
',然后用 include TagAccessor
包含它.ruby 文件可能如下所示:
One use of the lib directory (how I use it most often) is to share code between models to stay DRY. For example, if you are defining a tag_tokens
attribute on many different models for use with a tokenizer input, you could put that in "tag_accessor.rb" or something, place it in /lib
', and then include it with include TagAccessor
. The ruby file might look like:
module TagAccessor
def tag_tokens
tags.map(&:name).join(',')
end
def tag_tokens=(names)
self.tag_ids = names.split(",").uniq
end
end
(这是我的一个应用程序中的一个示例,这就是它如此具体的原因).然后在 Rails 3 中加载/lib 文件夹,把它放在你的 application.rb
中:
(This is an example from one of my apps, which is why it's so specific). Then to load the /lib folder in Rails 3, place this in your application.rb
:
config.autoload_paths += %W(#{config.root}/lib)
这篇关于Rails 库目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!