Rails lib directory

风格不统一 提交于 2019-12-22 01:13:03

问题


Question about lib directory.

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?

Thanks


回答1:


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

(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)


来源:https://stackoverflow.com/questions/7736773/rails-lib-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!