Finding a path without the file name - ruby

I'm attempting to create a a program that will give the full path to a file. This can be done with File.absolute_path, but it also adds the file name to the path. For example,
def test
path = File.absolute_path("test.rb")
puts path
end
#=> C:/users/james/myscripts/test/test.rb
I need to exclude the last part /test.rb so that the path would only contain: C:/users/james/myscripts/test. Is there a way to do this?

File.dirname will return the directory part of the path:
File.dirname(File.absolute_path("test.txt"))
# => C:/users/james/myscripts/test

If File.absolute_path("test.txt") gives the absolute path, and you want the directory of it, then that means that you just want the current directory. That is given by:
Dir.pwd

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"))

ruby: Can't create new file

I have a command line program that asks the user a set of questions and stores them in a file. The only problem is, I need it to create a new file and it won't.
Here is what I have tried:
File.open("path/to/file", "w")and File.open("path/to/file", "w+")
Both times I get this error
in 'initialize': No such file or directory # rb_sysopen - path/to/file (Errno::ENOENT)
Here is my current code:
File.open("path/to/file", "w") { |f| f.write(array.join("\n")) }
When someone writes path/to/file in a blog post or documentation, they don't intend for you to literally write path/to/file in your code. The point is that you need to edit that string to actually have the real path to your file, either as a relative path or an absolute path.
You said you are getting this error from the Ruby interpreter:
No such file or directory # rb_sysopen - path/to/file (Errno::ENOENT)
This means that in the current working directory, there is no directory named "path", or if there is a directory named "path", then it doesn't have a child directory named "to".
You could solve the immediate problem by running mkdir -p path/to, but that would be weird. It is better to just write an appropriate path in your code, pointing to a directory that already exists. Try changing the path to simply be output.txt (without any slashes) and see how that works.
Ensure you are using an absolute path, and if so, make sure the directory you want to store the file in is missing. Try creating it first:
require 'fileutils'
FileUtils.mkdir_p '/path/to'
File.open('/path/to/file', 'w') { ... }

Ruby FileUtils.mkdir_p is only creating parent directories

I have a controller in Rails, with an action that is meant to create a new directory.
This action should create the directory "/public/graph_templates/aaa/test". However, it leaves off the final directory "test". Why is this only creating parent directories?
def create_temporary_template
dir = File.dirname("#{Rails.root}/public/graph_templates/aaa/test")
FileUtils.mkdir_p dir
end
Docs: http://ruby-doc.org/stdlib-1.9.3/libdoc/fileutils/rdoc/FileUtils.html#method-c-mkdir_p
Because you use dir = File.dirname("#{Rails.root}/public/graph_templates/aaa/test"),
then the dir is "#{Rails.root}/public/graph_templates/aaa".
You could just pass the path to FileUtils.mkdir_p.
def create_temporary_template
dir = "#{Rails.root}/public/graph_templates/aaa/test"
FileUtils.mkdir_p dir
end
The problem is in your use of dirname:
File.dirname("/foo/bar")
# => "/foo"
dirname removes the last entry from the path. Per the documentation:
Returns all components of the filename given in file_name except the last one.
Usually that's the correct thing if your path contains a directory, or directory hierarchy, with the filename:
File.dirname("/foo/bar/baz.txt")
# => "/foo/bar"
But, in this case it's chopping off your desired trailing directory.
I'd recommend taking a look at the Pathname class that is included in Ruby's Standard Library. It wraps File, Dir, FileUtils, FileTest, and probably a Swiss-Army knife and kitchen sink into one class, making it very convenient to work on files and directories with one class.
require 'pathname'
dir = Pathname.new("/foo/bar/baz.txt")
# => "/foo/bar"
dir.mkpath # would create the path
I've found Pathname to be very useful, though it's still young.

Open file from same directory

Ok so with siriproxy it my lib folder along with the rb file for the plugin I have created a myconfig.yml file so I can change certain settings by writing to that file.
I have been able to write to the file but only if I include the full path all the way from the home directory down.
But is there not a way to open the file from the same directory i am in? I have tried every path combination I can think of.
There has to be one i am missing
If you use the following in your ruby file, you should get the absolute path where it is
File.expand_path(__FILE__)
From doc __FILE__
The name of the file currently being executed, including path relative to the directory where the application was started up (or the current directory, if it has been changed)
From doc File.expand_path
Converts a pathname to an absolute pathname.
As you probably want the directory, you should use File.dirname(__FILE__), so the path of your file myconfig.yml should be obtained with
File.join(File.expand_path(File.dirname(__FILE__)), 'myconfig.yml')
In more recent Ruby (>=2.0.0), you can use __dir__ (from Archonic's comment):
Returns the canonicalized absolute path of the directory of the file from which this method is called. It means symlinks in the path is resolved. If FILE is nil, it returns nil. The return value equals to File.dirname(File.realpath(FILE)).

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