Cross-Platform Means of Getting User's Home Directory in Ruby

Cross-platform means of getting user's home directory in Ruby?

The File.expand_path method uses the Unix convention of treating the tilde (~) specially, so that ~ refers to the current user's home directory and ~foo refers to foo's home directory.

I don't know if there's a better or more idiomatic way, but File.expand_path('~') should get you going.

Cross platform file names in Rails

I have solved problem with catching exception when file name is invalid and printing it for user.

begin
touch_file = open("#{@base_dir}#{file_name}", 'w')
if touch_file
#here goes code for opening file and inserting some text into it
end
rescue Exception => msg
#here I return msg.message to user

end

What's the best-practice way to find out the platform ruby is running on?

There's always:

begin
require 'win32console'
rescue LoadError
end

I find this easier to write and reason about that trying to decide for myself which OS I'm on and whether or not to load it.

Update: I was thinking win32console was built-in rather than a gem. I believe Win32API is available on all Windows installs, so it's a good proxy to test "Is this Windows?" (rather than "What OS is this, and is that Windows?").

begin
require 'Win32API'
windowsOS = true
rescue LoadError
windowsOS = false
end

if windowsOS
begin
require 'win32console'
rescue LoadError
# Prompt user to install win32console gem
end
end

Cross platform file names in Rails

I have solved problem with catching exception when file name is invalid and printing it for user.

begin
touch_file = open("#{@base_dir}#{file_name}", 'w')
if touch_file
#here goes code for opening file and inserting some text into it
end
rescue Exception => msg
#here I return msg.message to user

end

Cross-platform configuration, options, settings, preferences, defaults

What about storing in DB? It is cluster-friendly and has been working great for us. In my last job we used to store them in a directory server.

Java has support in the form of Preferences API.

I am not a .Net guy but I think they have User Profiles.

Python specific discussion: What's the official way of storing settings for python programs?

Ruby on Rails: Rails: Best practice to store user settings?

Ruby on rails cross-platform win/linux script

I wouldn't use a subcommand at all. The builtin Dir.glob should work in this case.

Something like:

Dir.glob("#{path}/**/**").each { |fileOrDir| do_something }

In any case, your find is recursive, but your dir wouldn't be.

If you really want to know if running on Windows, there are some Ruby-centric ways, but for years I have been checking for the WINDIR variable in the environment, e.g.

if ENV["WINDIR"]
puts "On Windows"
else
puts "Not Windows *probably*"
end

EDIT: Here is a tool I wrote years ago that generates a tree of Nodes and then displays them sorted in various ways.

def usage
puts <<END
Recursive listing of files or dirs, sortable by date or size or count.
rl [-cdfnrsuv] [-p pathname] [pathname ...]
Where:
pathname = Dir or file to process; default is ".".
-c = Sort by file count; default is sort by date.
-d = List dirs only, with their contents sizes and counts.
-f = List files only, no dirs or links.
-n = Sort by name; default is sort by date.
-p = Add pathname even if it starts with "-".
-r = Reverse sort order; default order is desc, except by name is asc.
-s = Sort by size; default is sort by date.
-u = Unsorted; default is sort by date.
-v = Verbose, including type, perms, and owner.
END
exit(1)
end # usage

class Node
attr_reader :path, :stat
def load(path)
@path, @stat, @children = path, File.lstat(path), []
@stat.directory? and Dir.glob("#{path}/*", File::FNM_DOTMATCH).each { |sub_path|
sub_path[-2,2] != "/." && sub_path[-3,3] != "/.." and @children << Node.new.load(sub_path)
}
self
end
def size
@size or @size = self.stat.directory? ? (@children.inject(0) { |acc, child| acc + child.size }) : @stat.size
end
def count
@count or @count = self.stat.directory? ? (@children.inject(0) { |acc, child| acc + child.count }) : 1
end
def to_a
@children.map { |child| child.to_a }.flatten + [self]
end
end # Node

only_dirs = only_files = by_count = by_name = by_sz = verbose = false; sort = 1; paths = []
while (arg = ARGV.shift)
arg =~ /^-[^-]*[h?]/ and usage
arg =~ /^-[^-]*c/ and by_count = true
arg =~ /^-[^-]*d/ and only_dirs = true
arg =~ /^-[^-]*f/ and only_files = true
arg =~ /^-[^-]*n/ and by_name = true
arg =~ /^-[^-]*r/ and sort *= -1
arg =~ /^-[^-]*s/ and by_sz = true
arg =~ /^-[^-]*u/ and sort = 0
arg =~ /^-[^-]*v/ and verbose = true
arg =~ /^-[^-]*p/ and paths << ARGV.shift
arg !~ /^-/ and paths << arg
end
nodes = (paths.empty? ? ["."] : paths).map { |path| Node.new.load(path).to_a }.flatten
if sort != 0
if by_sz then nodes.sort! { |a, b| sort * (2 * (b.size <=> a.size) + (a.path <=> b.path)) }
elsif by_count then nodes.sort! { |a, b| sort * (2 * (b.count <=> a.count) + (a.path <=> b.path)) }
elsif by_name then nodes.sort! { |a, b| sort * (a.path <=> b.path) }
else nodes.sort! { |a, b| sort * (2 * (b.stat.mtime <=> a.stat.mtime) + (a.path <=> b.path)) }
end
end
for node in nodes
next if only_dirs && ! node.stat.directory?
next if only_files && ! node.stat.file?
puts "%s %11s %6s %s%s" % [
node.stat.mtime.strftime("%Y-%m-%d %H:%M:%S"),
node.size.to_s.reverse.gsub(/(\d{3})(?=\d)(?!\d*\.)/, "\\1,").reverse,
node.count.to_s.reverse.gsub(/(\d{3})(?=\d)(?!\d*\.)/, "\\1,").reverse,
verbose ? "%-9s %6o %4d %4d " % [:ftype, :mode, :uid, :gid].map { |v| node.stat.send(v) } : "",
node.path]
end


Related Topics



Leave a reply



Submit