【问题标题】:Accessing text file in ruby gem在 ruby​​ gem 中访问文本文件
【发布时间】:2014-03-31 15:04:37
【问题描述】:

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

  _____
 |     |
 |_____|
 |
 |
 |

现在我制作了一个名为“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)

我在 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/'

【问题讨论】:

  • /lib/logo.txt 也不起作用..
  • 试试把logo.txt的全路径,也就是File.open("/usr/local/rvm/rubies/ruby-2.0.0-p451/lib/ruby/gems/2.0.0/gems/custom-0.0.1/lib/logo.txt")
  • 亲爱的,很多人会使用这个 gem,所以我不想硬编码完整路径,因为我不知道不同机器的路径是什么,而是这样做我想知道 gem 路径.

标签: ruby rubygems


【解决方案1】:

文件是相对于当前工作目录打开的,除非您指定完整路径。

为了避免硬编码完整路径,您可以使用__FILE__ 从Ruby 中获取当前文件的完整路径。事实上,您可以在 custom.gemspec 文件中看到非常相似的情况:

File.join( File.dirname(__FILE__), 'README')

我认为您可以像这样访问您的徽标文件:

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 中使用向后兼容的语法会更安全,以防您不确定某人在运行您的库时拥有什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2023-04-04
    • 2015-08-08
    相关资源
    最近更新 更多