user2784554
user2784554

Reputation: 5

How do I download/write file into a certain directory?

How can I specify the download directory? I tried this:

open("D:\Downloads" + filename, 'wb') do |io|
  response.read_body do |chunk|
    io.write chunk
  end
end

But it doesn't work. I don't even know in which directory the file is loaded.

Upvotes: 0

Views: 135

Answers (2)

the Tin Man
the Tin Man

Reputation: 160571

Take advantage of the File classes' ability to split and join paths:

open(File.join("D:/Downloads", filename), 'wb')

join and split are aware of the path separators and will do the right thing for you.

For instance:

filename = 'foo'

"D:\Downloads" + filename # => "D:Downloadsfoo"
File.join("D:\Downloads", filename) # => "D:Downloads/foo"

With Ruby it isn't necessary to use reverse-slashes (back-slash) in file-names on Windows. Ruby is smart enough to know the code is running on Windows, and automatically convert from forward-slashes to reverse-slashes if necessary.

See the IO documentation:

Ruby will convert pathnames between different operating system conventions if possible. For instance, on a Windows system the filename "/gumby/ruby/test.rb" will be opened as "\gumby\ruby\test.rb". When specifying a Windows-style filename in a Ruby string, remember to escape the backslashes:

"c:\\gumby\\ruby\\test.rb"

Our examples here will use the Unix-style forward slashes; File::ALT_SEPARATOR can be used to get the platform-specific separator character.

Now, look at the above sample code for using File.join. You're using "D:\Downloads" which gets converted to D:Downloads because of Ruby's double-quoted string interpreting \D as an attempt to escape D in error. As a result Ruby removes the single back-slash resulting in "D:Downloads", making what you intended to be an absolute path into a relative one, which would be rooted at the current directory when the code was run. Being aware that you don't need to use reverse-slashes removes the problem entirely allowing you to write "D:/Downloads" and make you, and Ruby, happy.

Alternatively, you could have used single-quotes like 'D:\Downloads', which Ruby would have happily accepted and understood to mean D:\\Downloads, but, again, given the above knowledge that you don't have to mess with back-slashes, makes it a moot-point.

"Backslashes in single quoted strings vs. double quoted strings" would be good additional reading for you.

Upvotes: 0

konsolebox
konsolebox

Reputation: 75548

Quote your path well. Also I think you need to add another \:

open("D:\\Downloads\\" + filename, 'wb') do |io|
  response.read_body do |chunk|
    io.write chunk
  end
end

Upvotes: 1

Related Questions