rshah
rshah

Reputation: 691

Why can't I find my file when using a function from a file inside a different folder?

So my project hierarchy is as follows:

.
└── project
    ├── main.rb
    ├── res
    │   └── test.txt
    └── modules
        └── printer.rb

My printer file looks like this containing one function which prints the contents of a text file into the console:

def print_file_dir(file)
  logo = File.open(__dir__ + file, 'r');
  logo.each_line do |line|
    puts line
  end
  logo.close
  puts
end

And I call my method like this:

require_relative 'modules/printer'
print_file_dir('/res/logo.txt')

However, when I call my print_file_dir method on test.txt in my res folder it throws the following error:

.../modules/printer.rb:3:in `initialize': No such file or directory @ rb_sysopen - .../modules/res/test.txt (Errno::ENOENT)

How can I stop it from getting files from the modules folder where the printer.rb file is located and instead from where I state the file relative to the initial directory?

Upvotes: 2

Views: 59

Answers (2)

Stefan
Stefan

Reputation: 114178

I would remove the file path logic from the method: (I've refactored the method a little bit)

# project/modules/printer.rb

def print_file(filename)
  IO.foreach(filename) { |line| puts line }
  puts
end

And instead pass the filename relative to the caller:

# project/main.rb

require_relative 'modules/printer'
print_file 'res/logo.txt'

or an absolute filename:

print_file '/path/to/project/res/logo.txt'

which could also be retrieved via __dir__:

print_file File.join(__dir__, 'res', 'logo.txt')

Upvotes: 0

Roan
Roan

Reputation: 932

When you change your code in your module to the code below, you will get the desired result:

    def print_file_dir(file)
        logo = File.open(Dir.getwd + file, 'r');
        logo.each_line do |line|
            puts line
        end
        logo.close
        puts
    end

Upvotes: 1

Related Questions