P
P
Piranis2014-06-11 04:58:56
Ruby on Rails
Piranis, 2014-06-11 04:58:56

Random rails filenames?

How to generate a random filename before saving. I will answer below.
For some, this is not news, but for the second time I am looking for the same solution, it's time to start writing myself :)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Piranis, 2014-06-11
@Piranis

The most adequate way suggested by @Vakiliy is the standard Paperclip function, which I overlooked. From here .

has_attached_file :avatar, {
    :url => "/system/:hash.:extension",
    :hash_secret => "longSecretString"
}

On stackoverflow, googling various variations of the same method. Tyts .
class Photo < Asset
  has_attached_file :image, :path => ":class/:id/:basename_:style.:extension"
  before_create :randomize_file_name
    private
      def randomize_file_name
        extension = File.extname(image_file_name).downcase
        self.image.instance_write(:file_name, "#{ActiveSupport::SecureRandom.hex(16)}#{extension}")
      end
end

Thanks again @Vakiliy , it was early in the morning and on my fourth coffee.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question