Class: UploadCache

Inherits:
Object
  • Object
show all
Defined in:
lib/upload_cache.rb

Defined Under Namespace

Modules: HtmlSafe

Constant Summary collapse

Version =
'1.2.1'
Readme =
<<-__
  NAME
    upload_cache.rb

  DESCRIPTION
    a small utility library to facility caching http file uploads between
    form validation failures.  designed for rails, but usable anywhere.

  USAGE
    in the controller

      def upload
        @upload_cache = UploadCache.for(params, :upload)

        @record = Model.new(params)

        if request.get?
          render and return
        end

        if request.post?
          @record.save!
          @upload_cache.clear!
        end
      end


    in the view

      <input type='file' name='upload />

      <%= @upload_cache.hidden %>

      <!-- optionally, you can show any uploaded upload -->

      <% if url = @upload_cache.url %>
        you already uploaded: <img src='<%= raw url %>' />
      <% end %>


    in a rake task

      UploadCache.clear!  ### nuke old files once per day

    upload_caches ***does this automatically*** at_exit{}, but you can still
    run it manually if you like.

__
UUIDPattern =
%r/^[a-zA-Z0-9-]+$/io
Age =
60 * 60 * 24
IOs =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, *args) ⇒ UploadCache

Returns a new instance of UploadCache.



242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/upload_cache.rb', line 242

def initialize(key, *args)
  options = Map.options_for!(args)

  @key = key
  @cache_key = UploadCache.cache_key_for(@key)
  @name = UploadCache.name_for(@cache_key)

  path = args.shift || options[:path]

  default = Map.for(options[:default])

  @default_url = default[:url] || options[:default_url] || UploadCache.default.url
  @default_path = default[:path] || options[:default_path] || UploadCache.default.path

  if path
    @path = path
    @dirname, @basename = File.split(@path)
    @value = File.join(File.basename(@dirname), @basename).strip
  else
    @path = nil
    @value = nil
  end

  if @path or @default_path
    @io = open(@path || @default_path, 'rb')
    IOs[object_id] = @io.fileno
    ObjectSpace.define_finalizer(self, UploadCache.method(:finalizer).to_proc)
  end
end

Instance Attribute Details

#basenameObject

Returns the value of attribute basename.



234
235
236
# File 'lib/upload_cache.rb', line 234

def basename
  @basename
end

#cache_keyObject

Returns the value of attribute cache_key.



230
231
232
# File 'lib/upload_cache.rb', line 230

def cache_key
  @cache_key
end

#default_pathObject

Returns the value of attribute default_path.



238
239
240
# File 'lib/upload_cache.rb', line 238

def default_path
  @default_path
end

#default_urlObject

Returns the value of attribute default_url.



237
238
239
# File 'lib/upload_cache.rb', line 237

def default_url
  @default_url
end

#dirnameObject

Returns the value of attribute dirname.



233
234
235
# File 'lib/upload_cache.rb', line 233

def dirname
  @dirname
end

#ioObject

Returns the value of attribute io.



236
237
238
# File 'lib/upload_cache.rb', line 236

def io
  @io
end

#keyObject

Returns the value of attribute key.



229
230
231
# File 'lib/upload_cache.rb', line 229

def key
  @key
end

#nameObject

Returns the value of attribute name.



231
232
233
# File 'lib/upload_cache.rb', line 231

def name
  @name
end

#pathObject

Returns the value of attribute path.



232
233
234
# File 'lib/upload_cache.rb', line 232

def path
  @path
end

#valueObject

Returns the value of attribute value.



235
236
237
# File 'lib/upload_cache.rb', line 235

def value
  @value
end

Class Method Details

.cache_key_for(key) ⇒ Object



111
112
113
114
115
# File 'lib/upload_cache.rb', line 111

def cache_key_for(key)
  key.clone.tap do |cache_key|
    cache_key[-1] = "#{ cache_key[-1] }_upload_cache"
  end
end

.cleanname(path) ⇒ Object



106
107
108
109
# File 'lib/upload_cache.rb', line 106

def cleanname(path)
  basename = File.basename(path.to_s)
  CGI.unescape(basename).gsub(%r/[^0-9a-zA-Z_@)(~.-]/, '_').gsub(%r/_+/,'_')
end

.clear!(options = {}) ⇒ Object



127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/upload_cache.rb', line 127

def clear!(options = {})
  return if UploadCache.turd?

  glob = File.join(root, '*')
  age = Integer(options[:age] || options['age'] || Age)
  since = options[:since] || options['since'] || Time.now

  Dir.glob(glob) do |entry|
    begin
      next unless test(?d, entry)
      next unless File.basename(entry) =~ UUIDPattern

      files = Dir.glob(File.join(entry, '**/**'))

      all_files_are_old =
        files.all? do |file|
          begin
            stat = File.stat(file)
            age = since - stat.atime
            age >= Age
          rescue
            false
          end
        end

      FileUtils.rm_rf(entry) if all_files_are_old
    rescue
      next
    end
  end
end

.defaultObject



182
183
184
# File 'lib/upload_cache.rb', line 182

def default
  @default ||= Map[:url, nil, :path, nil]
end

.finalizer(object_id) ⇒ Object



117
118
119
120
121
122
# File 'lib/upload_cache.rb', line 117

def finalizer(object_id)
  if fd = IOs[object_id]
    IO.for_fd(fd).close
    IOs.delete(object_id)
  end
end

.for(params, *args) ⇒ Object



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/upload_cache.rb', line 186

def for(params, *args)
  params = Map.for(params)
  options = Map.options_for!(args)

  key = Array(options[:key] || args).flatten.compact
  key = [:upload] if key.empty?

  upload = params.get(key)

  if upload.respond_to?(:read)
    tmpdir do |tmp|
      original_basename =
        [:path, :filename, :original_path, :original_filename].
        map{|msg| upload.send(msg) if upload.respond_to?(msg)}.compact.first
      basename = cleanname(original_basename)

      path = File.join(tmp, basename)
      open(path, 'wb'){|fd| fd.write(upload.read)}
      upload_cache = UploadCache.new(key, path, options)
      params.set(key, upload_cache.io)
      return upload_cache
    end
  end

  cache_key = cache_key_for(key)
  upload_cache = params.get(cache_key)

  if upload_cache
    dirname, basename = File.split(upload_cache)
    relative_dirname = File.expand_path(File.dirname(dirname))
    relative_basename = File.join(relative_dirname, basename)
    path = root + '/' + relative_basename
    upload_cache = UploadCache.new(key, path, options)
    params.set(key, upload_cache.io)
    return upload_cache
  end

  upload_cache = UploadCache.new(key, options)
  params.set(key, upload_cache.io) if upload_cache.io
  return upload_cache
end

.name_for(key, &block) ⇒ Object



165
166
167
168
169
170
171
# File 'lib/upload_cache.rb', line 165

def name_for(key, &block)
  if block
    @name_for = block
  else
    defined?(@name_for) ? @name_for[key] : [prefix, *Array(key)].compact.join('.')
  end
end

.prefix(*value) ⇒ Object



173
174
175
176
# File 'lib/upload_cache.rb', line 173

def prefix(*value)
  @prefix = value.shift if value
  @prefix
end

.prefix=(value) ⇒ Object



178
179
180
# File 'lib/upload_cache.rb', line 178

def prefix=(value)
  @prefix = value
end

.rootObject



72
73
74
# File 'lib/upload_cache.rb', line 72

def root
  @root ||= Dir.tmpdir
end

.root=(root) ⇒ Object



76
77
78
# File 'lib/upload_cache.rb', line 76

def root=(root)
  @root = File.expand_path(root)
end

.tmpdir(&block) ⇒ Object



95
96
97
98
99
100
101
102
103
104
# File 'lib/upload_cache.rb', line 95

def tmpdir(&block)
  tmpdir = File.join(root, uuid)

  if block
    FileUtils.mkdir_p(tmpdir)
    block.call(tmpdir)
  else
    tmpdir
  end
end

.turd?Boolean

Returns:

  • (Boolean)


161
162
163
# File 'lib/upload_cache.rb', line 161

def turd?
  @turd ||= !!ENV['UPLOAD_CACHE_TURD']
end

.urlObject



64
65
66
# File 'lib/upload_cache.rb', line 64

def url
  @url ||= "file:/#{ root }"
end

.url=(url) ⇒ Object



68
69
70
# File 'lib/upload_cache.rb', line 68

def url=(url)
  @url = '/' + Array(url).join('/').squeeze('/').sub(%r|^/+|, '').sub(%r|/+$|, '')
end

.versionObject



60
61
62
# File 'lib/upload_cache.rb', line 60

def version
  UploadCache::Version
end

Instance Method Details

#clear!Object



301
302
303
304
305
306
307
308
309
310
311
312
313
# File 'lib/upload_cache.rb', line 301

def clear!
  return if UploadCache.turd?

  begin
    FileUtils.rm_rf(@dirname) if test(?d, @dirname)
  rescue
    nil
  ensure
    @io.close rescue nil
    IOs.delete(object_id)
    Thread.new{ UploadCache.clear! }
  end
end

#hiddenObject



280
281
282
# File 'lib/upload_cache.rb', line 280

def hidden
  raw("<input type='hidden' name='#{ @name }' value='#{ @value }' class='upload_cache' />") if @value
end

#raw(*args) ⇒ Object



293
294
295
296
297
298
299
# File 'lib/upload_cache.rb', line 293

def raw(*args)
  string = args.join
  unless string.respond_to?(:html_safe)
    string.extend(HtmlSafe)
  end
  string.html_safe
end

#to_sObject



284
285
286
# File 'lib/upload_cache.rb', line 284

def to_s
  hidden.to_s
end

#urlObject



272
273
274
275
276
277
278
# File 'lib/upload_cache.rb', line 272

def url
  if @value
    File.join(UploadCache.url, @value)
  else
    @default_url ? @default_url : nil
  end
end