为什么 require_all 不能在 Sinatra 助手中工作?

Why doesn't require_all work inside a Sinatra helper?

所以我在 Sinatra 辅助模块中有一个函数 reload_config,它在下面 helpers.rb 中定义。

module Web
  module Helpers
    def reload_config
      require_all 'config/*.rb'
    end
  end
end

然后使用 helpers Web::HelpersWeb::Base 推荐的方式加载它。

config 中有一个名为 redis.rb 的文件,然后由 reload_config 加载。至少应该如此。在我的 config.ru(顶级)中调用 require_all 有效地加载了 redis.rb 的内容,但在我的辅助模块中它没有。

redis.rb 包含对 configatron.redis 的赋值(应该可以从任何范围级别访问,对吗?)

另一个令人不安的事实:如果我更改我给 require_all 的路径,它会引发异常。

此外,例如,如果我在 redis.rb 中写入 puts "Haaaaa!",它会在从 config.ru 加载时执行,但不会在从 helpers.rb 加载时执行。

这可能是什么原因造成的?如果它与词法作用域有关,那么为什么无法实际执行 putsconfigatron.foo = 'hello' 等语句?

请注意 require_allconfigatron 加载到 config.ru

解决方案就是用户 load_all 而不是 require_all

代码不会加载不是因为某些词法范围问题,而是因为 require_all 不会加载同一个文件两次。因此使用 load_all 解决了问题。