File paths in Ruby - ruby

So I want to make a file path relative to the directory it is in, in Ruby.
I have a project, and I want it to be able to find the file no matter what directory the project is unzipped into. (Say the code is run on different machines, for example) I can't figure it out for the life of me.
It seems for requires that I can do this:
require File.dirname(__FILE__) + '/comparison'
What can I do for a file that is in a different directory than my src folder?
Instead of listing,
file = 'C:/whole path/long/very_long/file.txt'
I'd like to say:
file = 'file.txt'
or
file = File.helpful_method + 'file.txt'

file = File.join(File.dirname(__FILE__), '..', 'another_dir', 'file.txt')
Replace '..', 'another_dir' with the relative path segments that reach 'file.txt'.

If you're running Ruby 1.9.2 or later, you can use require_relative instead:
require_relative '../somewhere/file.rb'
This doesn't solve the general problem of referring to files by their relative path, but if all you're doing is requiring the file, it should work.

Related

How to get filepath to file in another folder unix?

I am trying to write some data in one Ruby file to a file in another folder but I am having trouble identifying the path to get to the file I want to write to.
My current code is:
File.write('../csv_fixtures/loans.csv', 'test worked!')
And my folder structure is as follows:
Where I am trying to run my code in 'run_spec.rb' and write to 'loans.csv'.
Additionally, this is the error I am getting:
Give the path relative to the working directory, not the file that you call File.write from. The working directory is the place you've navigated to through cd before calling the ruby code. If you ran rspec from the root of your project, then the working directory will also be the root. So, in this case, it looks like it would be ./spec/csv_fixtures/loans.csv. You can run puts Dir.pwd to see the working directory that all paths should be relative to.
If you wanted to something more like require_relative, you have to use some sort of workaround to turn it into an absolute path, such as File.dirname(__FILE__) which gives the absolute path of the folder containing the current file:
path = File.join(File.dirname(__FILE__, "../csv_fixtures/loans.csv"))

Wildcard file requires in Ruby

As an example:
Dir[File.dirname(__FILE__) + "/support/**/*.rb"].each { |f| require f }
This is how RSpec requires all of the ruby files in the support directory and all subdirectories. I know this has to do with "/**/*". What does this mean in Ruby? How does it work?
File.dirname(__FILE__) is the directory where the file is. ** and * are UNIX wildcards. Adding "/support/**/*.rb to the directory points to any file that ends with .rb, which is under an arbitrary depth under the sub-directory support under that directory.
Passing that to Dir[] gives the array of such files. each iterates over such files, and require loads each file.
i believe that the /**/ part means Any directory , and the *.rb means any file that ends with .rb extention, regardless of it's name.
so, basically, you are getting any .rb file that are in any folder in
#{current_dir}/support/#{any_dir}/#{any_file_with_extention.rb}

How do I read from a file in the same directory?

I'm very much a beginner. I'd like to learn to read and write a file. Here's what I'm trying.
rdfile = File.open('bhaarat.txt', 'r+')
Unfortunately, this is returning "C:/directoriesblahblah/ubuntu3.rb:1:in 'initialize': No such file or directory - bhaarat.txt (Errno::ENOENT)
I have found solutions but I am not only new to Ruby but new to programming in general so I couldn't get an answer that made sense to me out of those.
Thanks in advance!
To obtain the path to the current file, you can use:
__FILE__
To obtain the directory in which the current file exists, you can use:
File.dirname(__FILE__)
To create a path from strings, you can use:
File.join('part1', 'part2', ...)
Therefore, to create a path to a file in that directory, you can use:
File.join(File.dirname(__FILE__), 'filename')
If your file name is bhaarat.txt, the above becomes:
File.join(File.dirname(__FILE__), 'bhaarat.txt')
If you replace that in your code, you will get:
rdfile = File.open(File.join(File.dirname(__FILE__), 'bhaarat.txt'), 'r+')
You can also make this a separate variable, if you want, to make the code more readable:
path = File.join(File.dirname(__FILE__), 'bhaarat.txt')
rdfile = File.open(path, 'r+')
The file is searched in the current directory, not the directory where the script is located.
C:\> ruby scripts\ubuntu3.rb
No such file or directory - bhaarat.txt
Move to the file location first and then run the script. For example, if the file is located in the same directory with the script:
C:\> cd scripts
C:\scripts> ruby ubuntu3.rb
File.read(File.join(__dir__, 'filename'))
Found something that did the trick. Searched a little harder and found this:
I changed my original code
rdfile = File.open('bhaarat.txt', 'r+')
to
rdfile = File.open(File.join(File.dirname(__FILE__),'bhaarat.txt'), 'r+')
and that makes it look in the directory of your .rb file, instead of the directory that your command prompt is currently in.

How do I load files from a specific relative path in Ruby?

I'm making a gem for internal use. In it, I load some YAML from another directory:
# in <project_root>/bin/magicwand
MagicWand::Configuration::Initializer.new(...)
# in <project_root>/lib/magicwand/configuration/initializer.rb
root_yaml = YAML.load_file(
File.expand_path("../../../../data/#{RootFileName}", __FILE__))
# in <project_root>/data/root.yaml
---
apple: 100
banana: 200
coconut: 300
I'd rather not depend on the location of data/root.yaml relative to initializer.rb. Instead, I'd rather get a reference to <project_root> and depend on the relative path from there, which seems like a smarter move.
First, is that the best way to go about this? Second, if so, how do I do that? I checked out the various File methods, but I don't think there's anything like that. I'm using Ruby 1.9.
Right now, I create a special constant and depend on that instead:
# in lib/magicwand/magicwand.rb
module MagicWand
# Project root directory.
ROOT = File.expand_path("../..", __FILE__)
end
but I'm not sure I like that approach either.
If there's a main file you always run you can use that file as a reference point. The relative path (between the current directory and) of that file will be in $0, so to get the relative path to data/root.yaml (assuming that is the relative path between the main file and root.yaml) you do
path_to_root_yaml = File.dirname($0) + '/data/root.yaml'

RubyZip - files from different directories have path in zip

I'm trying to use RubyZip to package up some files. At the moment I have a method which happily zips on particular directory and sub-directories.
def zip_directory(zipfile)
Dir["#{#directory_to_zip}/**/**"].reject{|f| reject_file(f)}.each do |file_path|
file_name = file_path.sub(#directory_to_zip+'/','');
zipfile.add(file_name, file_path)
end
end
However, I want to include a file from a completely different folder. I have a the following method to solve this:
def zip_additional(zipfile)
additional_files.reject{|f| reject_file(f)}.each do |file_path|
file_name = file_path.split('\\').last
zipfile.add(file_name, file_path)
end
end
While the file is added, it also copies the directory structure instead of placing the file at the root of the folder. This is really annoying and makes it more difficult to work with.
How can I get around this?
Thanks
Ben
there is setting to include (or exclude) the full path for zip libraries, check that setting
Turns out it was because the filename had the pull path in. My split didn't work as the path used a / instead of a . With the path removed from the filename it just worked.

Resources