访问ruby gem中的文本文件

Pra*_*pta 8 ruby rubygems

我使用ruby版本2.0.0,我在名为logo.txt的文本文件中制作了一些自定义徽标,如下所示:

  _____
 |     |
 |_____|
 |
 |
 |
Run Code Online (Sandbox Code Playgroud)

现在我创建了一个名为"custom"的gem,并将此文件放在lib/logo.txt下.现在我想在ruby gem下的脚本中打印这个文件,所以我这样写了.

file = File.open("lib/logo.txt")
contents = file.read
puts "#{contents}"
Run Code Online (Sandbox Code Playgroud)

但上面的代码会产生错误,例如:

/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)
Run Code Online (Sandbox Code Playgroud)

我在gemspec中包含了这个logo.txt文件,如下所示:

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/'
Run Code Online (Sandbox Code Playgroud)

Nei*_*ter 18

除非您指定完整路径,否则将相对于当前工作目录打开该文件.

为了避免硬编码完整路径,您可以使用Ruby获取当前文件的完整路径__FILE__.实际上你可以在custom.gemspec文件中看到一些非常相似的东西:

File.join( File.dirname(__FILE__), 'README')
Run Code Online (Sandbox Code Playgroud)

我想你可以这样找到你的徽标文件:

logo_path = File.join( File.dirname(__FILE__), '../logo.txt' )
file = File.open( logo_path )
Run Code Online (Sandbox Code Playgroud)

在Ruby 2.0中,您也有__dir__(可以替换File.dirname(__FILE__)),但这与Ruby 1.9不兼容.通常,如果您不确定某人在运行您的库时拥有什么,那么使用gems中的向后兼容语法会更安全.