How do I get the current working directory in IronRuby? - ironruby

I'm wondering how I can read the current working directory of a file being "parsed" by IronRuby. It appears the "execution directory" is the same as the ir.exe file.
I need this to create a relative path to content in a XNA solution without hardcoding the path.

From Class:Dir:
Dir.getwd => string
Dir.pwd => string
Returns the path to the current working directory of this process as a string.
Dir.chdir("/tmp") #=> 0
Dir.getwd #=> "/tmp"

I think I found the solution in Dir.pwd
Silly me forgot that pwd is not an acronym for password but for print working directory...
Embarassing :)

You can also use the CLR way of doing things if you feel like it:
include System
Environment.current_directory => clr_string

Related

Finding a path without the file name

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

How can I create a file on my desktop from a Ruby script?

I'm building a webcrawler and I want it to output to a new file that is timestamped. I've completed what I thought would be the more difficult part but I cannot seem to get it to save to the desktop.
Dir.chdir "~/Desktop"
dirname = "scraper_out"
filename = "#{time}"
Dir.mkdir(dirname) unless File.exists?(dirname)
Dir.chdir(dirname)
File.new(filename, "w")
It errors out on the first line
`chdir': No such file or directory # dir_chdir - ~/Desktop
I've read the documentation on FileUtils, File and cannot seem to find where people change into nested directories from the root.
Edit: I don't think FileUtils understands the ~.
~/ is not recognized by Ruby in this context.
Try:
Dir.chdir ENV['HOME']+"/Desktop"
This might help you
Create a file in a specified directory

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.

Delete hidden files in Ruby

Does anyone know how to delete all files in a directory with Ruby. My script works well when there are no hidden files but when there are (i.e .svn files) I cannot delete them and Ruby raises the Errno::ENOTEMPTY error.
How do I do that ?
If you specifically want to get rid of your svn files, here's a script that will do it without harming the rest of your files:
require 'fileutils'
directories = Dir.glob(File.join('**','.svn'))
directories.each do |dir|
FileUtils.rm_rf dir
end
Just run the script in your base svn directory and that's all there is to it (if you're on windows with the asp.net hack, just change .svn to _svn).
Regardless, look up Dir.glob; it should help you in your quest.
.svn isn't a file, it's a directory.
Check out remove_dir in FileUtils.
It probably has nothing to do with the fact, that .svn is hidden. The error suggest, that you are trying to delete a non empty directory. You need to delete all files within the directory before you can delete the directory.
Yes, you can delete (hiden) directory using FileUtils.remove_dir path.
I happend to just write a script to delete all the .svn file in the directory recursively. Hope it helps.
#!/usr/bin/ruby
require 'fileutils'
def svnC dir
d = Dir.new(dir)
d.each do |f|
next if f.eql?(".") or f.eql?("..")
#if f is directory , call svnC on it
path = dir + "/" + "#{f}"
if File.stat(path).directory?
if f.eql?(".svn")
FileUtils.remove_dir path
else
svnC path
end
end
end
end
svnC FileUtils.pwd
As #evan said you can do
require 'fileutils'
Dir.glob('**/.svn').each {|dir| FileUtils.rm_rf(dir) }
or you can make it a one liner and just execute it from the command line
ruby -e "require 'fileutils'; Dir.glob('**/.svn').each {|dir| FileUtils.rm_rf(dir) }"

What a safe and easy way to delete a dir in Ruby?

I'd like to delete a directory that may or may not contain files or other directories. Looking in the Ruby docs I found Dir.rmdir but it won't delete non-empty dir. Is there a convenience method that let's me do this? Or do I need to write a recursive method to examine everything below the directory?
require 'fileutils'
FileUtils.rm_rf(dir)
A pure Ruby way:
require 'fileutils'
FileUtils.rm_rf("/directory/to/go")
If you need thread safety: (warning, changes working directory)
FileUtils.rm_rf("directory/to/go", :secure=>true)
If some looking for answer on #ferventcoder comment -
Just a note, I found that with Windows and Ruby 1.9.3 (at least) FileUtils.rm_rf will follow links (symlinks in this case) and delete those files and folders as well. This was found based on creating a symlink with CreateSymbolicLinkW and then running FileUtils.rm_rf against a parent directory the symlinks are in. Not exactly expected behavior.
– ferventcoder
Safest way is to iterate path and delete it manually.
def rec_del(path):
if path is file call FileUtils.rm_rf - it is safe to delete even in windows
if dir call Dir.rmdir which will succeed for empty dir and dir symlink. else will get ENOTEMPTY for regular non empty dir.
iterate the dir and call rec_del for each item.
now call again Dir.rmdir which will succeed
The laziest way is:
def delete_all(path)
`rm -rf "#{path}"`
end

Resources