0

I need to get the user's home directory or at least his name.

Using FileUtils, I need to move files based on their account name, and using ~/ doesn't seem to work.

How would I get the user's account name?

Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
Chris Edwards
  • 3,514
  • 2
  • 33
  • 40

2 Answers2

0

I am not a rubymotion user yet, but in most rubies you can do

ENV["HOME"]

for the home directory and

ENV["USER"]

for the user to achieve exactly that using defined environment variables.

Patru
  • 4,481
  • 2
  • 32
  • 42
  • Thanks Patru, I have since found this post http://stackoverflow.com/questions/3020187/getting-home-directory-in-mac-os-x-using-c-language which suggests that may not be the best way. I'll give it (and the suggestions) a try and see :) – Chris Edwards May 21 '14 at 07:02
  • Of course you are right if you do not have control over what the rest of your process does with the environment. You could check out [this post](http://stackoverflow.com/questions/4190930/cross-platform-means-of-getting-users-home-directory-in-ruby) for some more suggestions on getting the home directory using ruby, especially an explanation of `Etc.getpwuid.dir` (and why it does not work on Windows). It is surprising, that ruby which tries to follow the POLS does not provide a platform independent way to this seemingly simple task. – Patru May 21 '14 at 09:39
0

To get to the document's path and create a new folder in OSX you could do.

directory = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true).first
directory = directory.stringByAppendingPathComponent("Sub Folder")

fileManager = NSFileManager.defaultManager

fileExists = fileManager.fileExistsAtPath(directory)
if (fileExists)
  NSLog("Folder already exists")
else
  if(!fileManager.createDirectoryAtPath(directory, withIntermediateDirectories:true, attributes: nil, error: nil))
    NSLog("Failed to create folder")
  else
    NSLog("Successfully created folder")
  end
end

If all you want is the user account's name you can use NSHost


For the home directory you could use NSHomeDirectory instead.

fm = NSFileManager.defaultManager
directory = NSSearchPathForDirectoriesInDomains(NSHomeDirectory, NSUserDomainMask, true).first
fm.contentsOfDirectoryAtPath(directory, error: nil).each do |file|
  puts file # outputs each file under the home directory
  // Copy file here using NSFileManager
end

You can then use NSFileManager's copyItemAtPath


ahmet
  • 4,955
  • 11
  • 39
  • 64
  • Awesome thanks, I'll give it a go! What I'm trying to do is copy a file from a path that stems from with the users home directory, to some other directory. I also don't know the files name, so am using wildcard matches (*), which hasn't been working so far... – Chris Edwards May 22 '14 at 11:43