我使用的是 ruby 版本 2.0.0,我在名为 logo.txt 的文本文件中制作了一些自定义 Logo ,如下所示:
_____
| |
|_____|
|
|
|
现在我制作了一个名为“custom”的 gem 并将此文件放在 lib/logo.txt 下。现在我想在 ruby gem 下的脚本中打印这个文件,所以我这样写。
file = File.open("lib/logo.txt")
contents = file.read
puts "#{contents}"
但是上面的代码会产生错误,比如:
/usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/gems/2.0.0/gems/custom-0.0.1/lib/custom/custom.rb:1551:in `initialize': No such file or directory - lib/logo.txt (Errno::ENOENT)
我将这个 logo.txt 文件包含在 gemspec 中,如下所示:
Gem::Specification.new do |s|
s.name = "custom"
s.version = VERSION
s.author = "Custom Wear"
s.email = "custom@custom.com"
s.homepage = "http://custom.com"
s.summary = "custom wera"
s.description = File.read(File.join(File.dirname(__FILE__), 'README'))
s.license = 'ALL RIGHTS RESERVED'
s.files = [""lib/custom.rb", "lib/custom/custom.rb", "lib/custom /version.rb","lib/logo.txt"]
s.test_files = Dir["spec/**/*"]
s.executables = [ 'custom' ]
s.require_paths << 'lib/'
最佳答案
文件相对于当前工作目录打开,除非您指定完整路径。
为了避免硬编码完整路径,您可以使用 __FILE__
从 Ruby 获取当前文件的完整路径。事实上,您可以在 custom.gemspec
文件中看到非常相似的情况:
File.join( File.dirname(__FILE__), 'README')
我认为您可以像这样获取 Logo 文件:
logo_path = File.join( File.dirname(__FILE__), '../logo.txt' )
file = File.open( logo_path )
在 Ruby 2.0 中,您还有 __dir__
(可以替换 File.dirname(__FILE__)
),但它与 Ruby 1.9 不兼容。一般来说,在 gems 中使用向后兼容的语法会更安全,以防您不确定某人在运行您的库时拥有什么。
关于ruby - 访问ruby gem中的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22754576/