ruby - 访问ruby gem中的文本文件

标签 ruby rubygems

我使用的是 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/

相关文章:

ruby - 如何使用 Ruby 列出远程网站的目录

ruby-on-rails - Bundler 无法在 Rails 中的 bundle 安装中找到兼容版本

ruby - 有没有包含大多数英语单词的 ruby​​ gem 或 API?

ruby - 命令行和参数处理

ruby-on-rails - ActiveSupport::Duration hours/minutes/seconds 总是秒?

使用时 Rubygems 2.0.14 不是线程安全的 bundle 程序安装消息 - RUBYGEMS VERSION : 2. 4.5.1

ios - 使用 Vuforia 8.5.9 构建 Unity iOS 版本 2019.3.0f1 时出现此构建时间错误

ruby - 在 Ruby 中,是否有与 Smalltalk 中等效的 printNl 方法?

Ruby IMAP 库 : How can I show all messages in a folder?

ruby - 在 OS X Lion 上安装 OpenCV