【问题标题】:Requiring files in Ruby在 Ruby 中需要文件
【发布时间】:2012-03-16 14:12:14
【问题描述】:

我正在 Sinatra 中构建一个网络应用程序,我在 /lib/checkers/ 中有一堆文件

我目前要求他们这样做:

require File.expand_path(File.dirname(__FILE__) + '/lib/checkers/board.rb')
require File.expand_path(File.dirname(__FILE__) + '/lib/checkers/checker.rb')

这似乎很愚蠢,但我已经尝试过

require '/lib/checkers'

require '/lib/checkers/' 

require File.expand_path(File.dirname(__FILE__) + 'lib/checkers/')

以及与它们相同的其他变体,但似乎没有任何效果。你能帮忙吗?

【问题讨论】:

  • lib 目录放入您的包含路径$:(如果它不存在),然后只需将require 'checkers/board'require 'checkers/checker' 放入。
  • 不,你不需要使用其他问题中的技术。

标签: ruby path require


【解决方案1】:
require_relative 'lib/checkers/board'
require_relative 'lib/checkers/checker'

这就是我一直这样做的方式。这位于我的主应用程序文件中,该文件始终位于根目录中。我不确定它在其他文件中的表现如何,尽管我相信它与调用文件有关。

另外,settings.root 将返回您应用的根目录,在任何地方都不需要File.dirname(__FILE__)

这在 Ruby 1.9 中有效,无需通过上述 cmets 进行任何特殊技术。

如果你使用的是 1.8,你可以这样做

require './lib/checkers/board'
require './lib/checkers/checker'

this question 中列出了 1.8 的其他技术。

【讨论】:

  • 请注意,require_relative 仅在 Ruby >= 1.9.2 中可用。如果您选择使用此解决方案,请参阅this post 了解更多信息。
  • @louism 感谢您提醒我。我从 1.9 开始学习 Ruby,所以我倾向于忘记 1.8 中的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-10
  • 2014-12-03
  • 2015-10-19
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多