Delete files in ruby

I use a media camcorder to download files. I created a system for users to mark images as inappropriate and administrators to delete images. From what I can say, when you call destroy on the image, only the path name from the table will be deleted. Is there any way for ruby ​​to actually delete the file itself? Or should the rails automatically delete the file when I destroy the image path?

+44
ruby ruby-on-rails ruby-on-rails-3 carrierwave
Jul 01 2018-11-21T00:
source share
3 answers

Not sure what CarrierWave offers for this, but you can use FileUtils in the standard Ruby library with an ActiveRecord callback.

For example,

 require 'FileUtils' before_destroy :remove_hard_image def remove_hard_image FileUtils.rm(path_to_image) end 

Sidenote: This code is from memory.

+56
Jul 01 2018-11-11T00:
source share

Like @mu_is_too_short, you can use File # delete .

Here's a snippet of code that you could use as an assistant, with a little tweaking in your rails application.

 def remove_file(file) File.delete(file) end 

or if you have a file name stored in a file

 def remove_file(file) File.delete("./path/to/#{file}") end 
+88
Feb 06 '14 at 22:39
source share

If you want to delete the file, but do not want to specify the full file name, you can use below.

It can also be used to delete many files or all files in a directory with a specific extension ...

 file = Rails.root.join("tmp", "foo*") 

or

 file = Rails.root.join("tmp", ".pdf") 



 files = Dir.glob(file) #will build an array of the full filepath & filename(s) files.each do |f| File.delete(f) end 
+1
Sep 20 '16 at 3:08
source share



All Articles