本文介绍了如何包含所有lib文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用简单的方法扩展核心Array类:

I want to extend core Array class with simple method:

class Array
  def to_hash
    result = Hash.new
    self.each { |a| result[a] = '' }
    result
  end
end

我将array.rb放到lib/core_ext中,并试图通过以下方式在application.rb中要求它

I put array.rb into lib/core_ext and tried to require it in application.rb by

config.autoload_paths += %W(#{config.root}/lib)
config.autoload_paths += Dir["#{config.root}/lib/**/"]

但是如果尝试在模型方法中使用它,仍然会得到undefined method 'to_hash' for ["var1", "var2", "var3"]:Array.当然,更改代码后,我会重新启动服务器.

But still get undefined method 'to_hash' for ["var1", "var2", "var3"]:Array if tried to use it in model method. Of course I rebooted the server after code changes.

推荐答案

执行此操作的方法是,将以下内容添加到config/initializers

Once way you can do this is by adding the following to one of the files in config/initializers

require 'core_ext/array`

您的所有autoload_paths配置值所做的就是使路径在请求类/文件时可用.在我的应用中,我的文件结构可能如下所示

All your autoload_paths config value does is make the paths available for when the classes/files are requested. In my app I might have some file structure as follows

- lib/
  |
  |- deefour.rb
  |- deefour/
     |
     |- core_ext.rb

在我的deefour.rb中,

require 'deefour/core_ext'

config/initializers内部,我有一个deefour.rb文件,其中仅包含

and inside config/initializers I have a deefour.rb file containing simply

require 'deefour'

您设置的自动加载配置值将导致Rails看起来自动加载lib/deefour/core_ext.rb的唯一方法是,如果您对该文件中存在的类Deefour::CoreExt进行了某些调用.这就是为什么初始化程序中的require 'deefour'行知道自动加载lib/deefour.rb文件的原因.

The only way the autoload config value you set will cause Rails to look auto load lib/deefour/core_ext.rb is if you had some call to a class Deefour::CoreExt that existed in that file. This is why my require 'deefour' line in the initializer knows to autoload the lib/deefour.rb file.

lib/deefour.rb中的显式require 'deefour/core_ext'具有相同的目的,因为它也没有遵循Ruby/Rails期望的标准类名到目录的映射.

The explicit require 'deefour/core_ext' in lib/deefour.rb serves the same purpose, since it too does not follow the standard class-name-to-directory mapping Ruby/Rails will expect.

这篇关于如何包含所有lib文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-12 21:00