forked from shrinerb/shrine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_metadata.rb
72 lines (56 loc) · 1.78 KB
/
add_metadata.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# frozen_string_literal: true
class Shrine
module Plugins
# Documentation lives in [doc/plugins/add_metadata.md] on GitHub.
#
# [doc/plugins/add_metadata.md]: https://github.com/shrinerb/shrine/blob/master/doc/plugins/add_metadata.md
module AddMetadata
def self.configure(uploader)
uploader.opts[:metadata] ||= []
end
module ClassMethods
def add_metadata(name = nil, **options, &block)
opts[:metadata] << [name, options, block]
metadata_method(name) if name
end
def metadata_method(*names)
names.each { |name| _metadata_method(name) }
end
private
def _metadata_method(name)
self::UploadedFile.send(:define_method, name) do
metadata[name.to_s]
end
end
end
module InstanceMethods
def extract_metadata(io, context = {})
metadata = super
context = context.merge(metadata: metadata)
extract_custom_metadata(io, context)
metadata
end
private
def extract_custom_metadata(io, context)
opts[:metadata].each do |name, options, block|
result = instance_exec(io, context, &block)
metadata = {}
if name
metadata[name.to_s] = result
else
metadata.merge!(result) if result
end
# convert symbol keys to strings
metadata.keys.each do |key|
metadata[key.to_s] = metadata.delete(key) if key.is_a?(Symbol)
end
context[:metadata].merge!(metadata)
# rewind between metadata blocks
io.rewind
end
end
end
end
register_plugin(:add_metadata, AddMetadata)
end
end