Uploader::UniqFilename to generate unique file name.
# lib/uploader/uniq_filename.rb
module Uploader
module UniqFilename
extend ActiveSupport::Concern
def filename
return if original_filename.blank?
if file.extension.present?
"#{secure_token}.#{file.extension}"
else
secure_token
end
end
protected
def secure_token(length = 10)
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.hex(length/2))
end
end
endUploader::UrlWithHost overrides the default url method, which returns the file url with host (for CDN purpose for example). Just configure hosts in CONFIG const.
module Uploader
module UrlWithHost
class Host
class << self
def config
CONFIG[:uploader] || {}
end
def list
config['hosts'] || []
end
end
end
extend ActiveSupport::Concern
included do
alias_method :url_without_host, :url
define_method :url_with_host do |options ={}|
path = url_without_host(options)
return path if path.blank?
return path if path.start_with?('http')
hosts = Host.list
return path if hosts.length.zero?
hosts[model.id.to_i % hosts.length] + path.to_s
end
alias_method :url, :url_with_host
end
end
end