1

I have a file object which is of type Rails ActionDispatch::Http::UploadedFile.

I need to overwrite user assigned filename with a generic name while preserving the extension of the file. This is how I have the code implemented currently. Is there are a way better and elegant way of writing this in Ruby.

extension = File.extname(file_name.original_filename)
file_name.original_filename = "hello#{extension}"
Ramya
  • 107
  • 1
  • 1
  • 12

2 Answers2

0
file.original_filename.sub!(/.*\./, "hello.")

this works because .* is greedy and will swallow everything up to the last . it finds. That just happens to be the the one before the extension.

Or to do an exact replacement, you can just do:

file_name.original_filename = "hello" + File.extname(file_name.original_filename)

technically, still a oneliner lol.

Bassel Samman
  • 802
  • 5
  • 11
0

Edit: I misunderstood. (I thought new_name included an extension that was to be replaced by "old_fname"'s extension.) As @Bassel says (thanks, Bassel), it should simply be:

old_fname = "/a/b/c.hello" 
new_fname = "/d/e/f"

new_fname += File.extname(old_fname)
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
  • Or, since we are talking about string you can do new_fname += File.extname(old_fname) – Bassel Samman Oct 30 '15 at 00:21
  • @Bassel, that would not replace `new_fname`'s extension; it would merely append `old_fname`'s extension to `new_fnane`. – Cary Swoveland Oct 30 '15 at 00:50
  • That is what he is trying to do. He doesn't have to replace the extension because he shouldn't have one yet. Just needs to make sure the new filename uses the old filenames extension. – Bassel Samman Oct 30 '15 at 02:42