Accessing text file in ruby gem

ruby, rubygems

Solution

The file is opened relative to the current working directory, unless you specify the full path.

In order to avoid hard-coding full paths, you can get the full path of the current file from Ruby using `__FILE__`. In fact you can see in the `custom.gemspec` file something very similar going on:

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

I think you can get to your logo file like this:

logo_path = File.join( File.dirname(__FILE__), '../logo.txt' )
file = File.open( logo_path )

In Ruby 2.0, you also have `__dir__` (which can replace `File.dirname(__FILE__)`) but that would not be compatible with Ruby 1.9. Generally you are safer using backward-compatible syntax in gems in case you are not sure what someone has when they run your library.

Problem

I am using ruby version 2.0.0 , I made some custom logo in text file named logo.txt like this: ``` _____ | | |_____| | | | ``` Now i made a gem with name of "custom" and placed this file under lib/logo.txt . Now i wants to print this file in my script under ruby gem so i wrote in this way. ``` file = File.open("lib/logo.txt") contents = file.read puts "#{contents}" ``` But above code produce errors, like: ``` /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) ``` I include this logo.txt file in gemspec as per below: ``` 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/' ```

Original source