Where do the files created with File.new actually get stored in Ruby? - ruby

I am creating files from within Ruby scripts and adding stuff to them. But where are these files stored that I am creating?
I'm very new to this, sorry!

The files are created at whatever location you specified. For instance:
f = File.new("another_test.txt","w+")
that will create the file in the current working directory. You specify the path along with the file name. For example:
f = File.new("~/Desktop/another_test.txt","w+") # will create the file on the desktop.
For more details, check the File documentation.
Updated:
Included mu is too short correction.

Related

Create a directory structure from a path in gradle/groovy

I am implementing a diff package generation task in my project's gradle build from the git command line output. Currently I have a method which will give me a list of changed files from git diff --name-only. What I would like to do is create a directory structure in a new directory which matches the paths of each file. For example: inputting the string repo/dir/file.java would create in an output directory if not already created and inside it the directories head/repo/dir with the current file.java and prev/repo/dir with the previous file.java.
My current plan is to split the string repo/dir/file.java on the forward slash, and create directories until the last element of the split result, then write the file there. but nothing I have been able to come up with in gradle is nice or clean. I am wondering if there is a nicer way to create directories from a string like that.
My current plan is to split the string repo/dir/file.java on the forward slash, and create directories until the last element of the split result
Rather than splitting your string manually, you could try using File.mkdirs():
File newDirectoryStructureParent = new File('some/path/to/parent/dir')
def s = 'repo/dir/file.java'
def newContainer = new File(s, newDirectoryStructureParent).getParent()
newContainer.mkdirs()
everyone
In this part of my code you can just work around Path not File!
At the first you can define Path and second need check that path exist or not, if not mkdirs can make it ;)
Its help when you unknown about that path exist or not /
File fullPath = new File('/tmp/Test1')
if (!fullPath.exists())
fullPath.mkdirs()

sql loader without .dat extension

Oracle's sqlldr defaults to a .dat extension. That I want to override. I don't like to rename the file. When googled get to know few answers to use . like data='fileName.' which is not working. Share your ideas, please.
Error message is fileName.dat is not found.
Sqlloder has default extension for all input files data,log,control...
data= .dat
log= .log
control = .ctl
bad =.bad
PARFILE = .par
But you have to pass filename without apostrophe and dot
sqlloder pass/user#db control=control data=data
sqloader will add extension. control.ctl data.dat
Nevertheless i do not understand why you do not want to specify extension?
You can't, at least in Unix/Linux environments. In Windows you can use the trailing period trick, specifying either INFILE 'filename.' in the control file or DATA=filename. on the command line. WIndows file name handling allows that; you can for instance do DIR filename. at a command prompt and it will list the file with no extension (as will DIR filename). But you can't do that with *nix, from a shell prompt or anywhere else.
You said you don't want to copy or rename the file. Temporarily renaming it might be the simplest solution, but as you may have a reason not to do that even briefly you could instead create a hard or soft link to the file which does have an extension, and use that link as the target instead. You could wrap that in a shell script that takes the file name argument:
# set variable from correct positional parameter; if you pass in the control
# file name or other options, this might not be $1 so adjust as needed
# if the tmeproary file won't be int he same directory, need to be full path
filename=$1
# optionally check file exists, is readable, etc. but overkill for demo
# can also check temporary file does not already exist - stop or remove
# create soft link somewhere it won't impact any other processes
ln -s ${filename} /tmp/${filename##*/}.dat
# run SQL*Loader with soft link as target
sqlldr user/password#db control=file.ctl data=/tmp/${filename##*/}.dat
# clean up
rm -f /tmp/${filename##*/}.dat
You can then call that as:
./scriptfile.sh /path/to/filename
If you can create the link in the same directory then you only need to pass the file, but if it's somewhere else - which may be necessary depending on why renaming isn't an option, and desirable either way - then you need to pass the full path of the data file so the link works. (If the temporary file will be int he same filesystem you could use a hard link, and you wouldn't have to pass the full path then either, but it's still cleaner to do so).
As you haven't shown your current command line options you may have to adjust that to take into account anything else you currently specify there rather than in the control file, particularly which positional argument is actually the data file path.
I have the same issue. I get a monthly download of reference data used in medical application and the 485 downloaded files don't have file extensions (#2gb). Unless I can load without file extensions I have to copy the files with .dat and load from there.

How can I specify the file location to write and read from in Ruby?

So, I have a function that creates an object specifying user data. Then, using the Ruby YAML gem and some code, I put the object to a YAML file and save it. This saves the YAML file to the location where the Ruby script was run from. How can I tell it to save to a certain file directory? (A simplified version of) my code is this
print "Please tell me your name: "
$name=gets.chomp
$name.capitalize!
print "Please type in a four-digit PIN number: "
$pin=gets.chomp
I also have a function that enforces that the pin be a four-digit integer, but that is not important.
Then, I add this to an object
new_user=Hash.new (false)
new_user["name"]=$name
new_user["pin"]=$pin
and then add it to a YAML file and save it. If the YAML file doesn't exist, one is created. It creates it in the same file directory as the script is run in. Is there a way to change the save location?
The script fo save the object to a YAML file is this.
def put_to_yaml (new_user)
File.write("#{new_user["name"]}.yaml", new_user.to_yaml)
end
put_to_yaml(new_user)
Ultimately, the question is this: How can I change the save location of the file? And when I load it again, how can i tell it where to get the file from?
Thanks for any help
Currently when you use File.write it takes your current working directory, and appends the file name to that location. Try:
puts Dir.pwd # Will print the location you ran ruby script from.
You can specify the absolute path if you want to write it in a specific location everytime:
File.write("/home/chameleon/different_location/#{new_user["name"]}.yaml")
Or you can specify a relative path to your current working directory:
# write one level above your current working directory
File.write("../#{new_user["name"]}.yaml", new_user.to_yaml)
You can also specify relative to your current executing ruby file:
file_path = File.expand_path(File.dirname(__FILE__))
absolute_path = File.join(file_path, file_name)
File.write(absolute_path, new_user.to_yaml)
You are supplying a partial pathname (a mere file name), so we read and write from the current directory. Thus you have two choices:
Supply a full absolute pathname (personally, I like to use the Pathname class for this); or
Change the current directory first (with Dir.chdir)

Visual Studio Setup Project - How to Obtain the Directory Path from a File-Search Launch Condition

I am looking for a way to add File(s) to an existing directory that has a random name as part of a Visual Studio Setup Project and I hoped someone might be able to help me solve this puzzle please.
I have been attempting to obtain the discovered path property of the directory using a Launch Condition; Unfortunately this method returns the full file path including the filename, which cannot be used as a directory property.
The directory in question takes the form [AppDataFolder]Company\Product\aaaaaaaaaaaa\
where aaaaaaaaaaaa is a random installation string.
Within the Launch Condition Setup I check for the directory's existence by searching for a file that would appear inside it,
Search Target Machine
(Name): File marker
Filename: sample.txt
Folder: [AppDataFolder]Company\Product\
Property: DIRFILE
Launch Condition
(Name): File marker exists
Condition: DIRFILE
In the Setup Project I add the file I wish to insert, with the details
Condition: DIRFILE
Folder: 'Installation folder'
Then in File System Setup I add a new folder entry for the random directory aaaaaaaaaaaa
(Name): Installation folder
Condition: DIRFILE
DefaultLocation: [DIRFILE]\..\ *Incorrect*
Property [DIRLOCATION]
As you can see the installer detects the existence of the marker file but, instead of placing my file at the same location, when using [DIRFILE] the installer would incorrectly try and insert it INTO the file;
This is because the file path was returned
[AppDataFolder]Company\Product\aaaaaaaaaaaa\sample.txt
where I instead need the directory path
[AppDataFolder]Company\Product\aaaaaaaaaaaa
Therefore I was wondering if it was possible to return the directory the file was found in from Search Target Machine (as opposed to the file location of the file), if I could extract the directory path by performing a string replace of the filename on the file location DIRFILE within the DefaultLocation field in File System Setup, or if perhaps there is even another method I am missing?
I'm also very interested in a simple solution for this, inside the setup project.
The way I did solve it was to install the files to a temporary location and then copy them to the final location in an AfterInstall event handler. Not a very elegant solution! Since it no longer care about the user selected target path I removed that dialog. Also I needed to take special care when uninstalling.
public override void OnAfterInstall(IDictionary savedState)
{
base.OnAfterInstall(savedState);
// Get original file folder
string originDir = Context.Parameters["targetdir"];
// Get new file folder based on the dir of sample.txt
string newDir = Path.GetDirectoryName(Context.Parameters["dirfile"]);
// Application executable file name
// (or loop for all files on the path instead)
string filename = "ApplicationName.exe";
// Move or copy the file
File.Move(Path.Combine(originDir, filename), Path.Combine(newDir, filename)));
}

how to make a generic path for a log file in Ruby

Here I am creating the logs folder under the current path of the directory using Dir::pwd. But I want to change this to pick the directory path from config files which will run in any other machines.
date_directory= "#{Dir::pwd}/logs/#{DateHelper.getDirectoryYearStamp}/#{DateHelper.getDirectoryMonthStamp}/#{DateHelper.getDirectoryDateStamp}/"
FileUtils.mkdir_p(date_directory) unless Dir.exists?(date_directory)
I tired with giving the absolute path and it works. But how do I make the directory by passing the relative path?
You are allready using a relative path, so is is generic solution, the subfolder of your current folder is a relative position. Is the code you published working ? But inside your question you mention config files, is it that what you want ? What kind of file ? a yaml, ini or of a simple text file ?
If a simple textfile you can do with
path = File.read("#{File.dirname(__FILE__)}/path.txt")
EDIT: based on your comment, the following snippets wil create a logfile a day in the /some/x/y/z
folder.
require 'logger'
$log = Logger.new("/some/x/y/z/logs.txt", 'daily' )
$log.info "teststring"
gives in the file "C:\some\x\y\z\logs.txt"
# Logfile created on 2013-04-05 13:17:27 +0200 by logger.rb/31641
I, [2013-04-05T13:20:19.811837 #3300] INFO -- : teststring

Resources