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)).
Related
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"))
So I'm making a game with Ruby/Gosu and the lines to load all the images look like this:
#image_name = Gosu::Image.new(self, 'C:\Users\Carlos\Desktop\gamefolder\assets\bg.jpg', false)
I want to refer to them based on their location relative to the referring file. The file which includes the above line is in C:\Users\Carlos\Desktop\gamefolder\, so I would think I could just change the above to '\assets\bg.jpg' or 'assets\bg.jpg', but this doesn't work.
The specific error is "Could not load image assets/bg.jpg using either GDI+ or FreeImage: Unknown Error (Runtime Error)."
If you want to get the current directory (of your execution context, not necessarily the file you're 'in'), just use Dir.pwd. Output this to console to check that your current directory is actually gamefolder.
To get the current directory of your actual ruby file (relative to Dir.pwd), use __FILE__, e.g.
File.dirname(__FILE__)
Pass that to File.expand_path to get a fully-qualified path. You can do a little sanity check by making sure File.exists?("#{File.expand_path File.dirname __FILE__}/assets/bg.jpg") returns true.
(Try File.expand_path('assets/bg.jpg')...that might be all you need here.)
I have an image with the filename media_httpfarm3static_mAyIi.jpg.
I would like to search the parent folder and all subfolders of that parent folder for a file that contains that name - it doesn't have to be the EXACT name, but must contain that string.
E.g. this file should be returned: 11605730-media_httpfarm3static_mAyIi.jpg
So this is a 2-part question:
How do I achieve the above?
Once I have the file, how do I return the path for that file?
Use Dir::[] and File::absolute_path:
partial_name = "media_httpfarm3static_mAyIi.jpg"
Dir["../**/*#{partial_name}"].each do |filename|
puts File.absolute_path(filename)
end
This uses the glob "../**/*media_httpfarm3static_mAyIi.jpg" (go up one directory, then search all sub directories (recursively), for any file ending in the partial string "media_httpfarm3static_mAyIi.jpg". The relative paths are then returned in an Array.
You can use Array#each, Array#map, etc. to convert this into what you need. To convert a relative path, into an absolute path, just pass it to File::absolute_path.
Once you have the absolute path, you can use it to open the file, read the file, etc.
On File Paths
The glob "../**/*media_httpfarm3static_mAyIi.jpg" is relative to the current working directory. Normally, this is the directory from which the program was run. Not the directory of the source file. This can change using various utilities to change it.
To always use a glob relative to the source code file, try:
Dir[File.expand_path('../**/*#{partial_name}', __FILE__)]
You can also use:
Dir[File.join(__dir__, "..", "**", "*#{partial_name}")]
Note: __dir__ was added in Ruby 2.0. For older versions of ruby use File.dirname(__FILE__)
In the first code sample File::absolute_path was used. In the last sample File::expand_path is used. In most situations these can be used interchangeably. There is a minor difference, per the documentations:
File::absolute_path
Converts a pathname to an absolute pathname. Relative paths are
referenced from the current working directory of the process unless
dir_string is given, in which case it will be used as the starting
point. If the given pathname starts with a “~” it is NOT expanded, it
is treated as a normal directory name.
File::expand_path
Converts a pathname to an absolute pathname. Relative paths are
referenced from the current working directory of the process unless
dir_string is given, in which case it will be used as the starting
point. The given pathname may start with a “~”, which expands to the
process owner’s home directory (the environment variable HOME must be
set correctly). “~user” expands to the named user’s home directory.
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
I need to get the main project working directory, for example I have a project folder structure like,
Projectmainfolder->
SourceCodeFolder
AnotherFolder
I have my all code files in sourceCodeFolder, and now I want to get or print Projectmainfolder path, Kindly let me know if there is a way to get the location path of the root project folder.
This will give you the path to the current file.
__FILE__
In order to expand a relative path, do this:
File.expand_path("../../", __FILE__)
if you start your script from the Projectmainfolder directory, Dir.getwd should print you the path you want. Or did you mean something different?