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 = "[email protected]"
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/'
Package that may contain Ruby programs and libraries; saved in a self-contained format called a "gem;" can be installed using the RubyGems package manager application included with the Ruby software. Ruby GEM files can be installed using the "gem install GEMNAME [options]" command.
Overview. The IO instance is the basis for all input and output operations in Ruby. Using this instance, we can read a file and get its contents line by line using the foreach() method. This method takes the name of the file, and then a block which gives us access to each line of the contents of the file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With