Module: EchoUploads::Model

Extended by:
ActiveSupport::Concern
Defined in:
lib/echo_uploads/model.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#echo_uploads_dataObject



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/echo_uploads/model.rb', line 18

def echo_uploads_data
  Base64.encode64(JSON.dump(self.class.echo_uploads_config.inject({}) do |hash, (attr, cfg)|
    metas = send("#{attr}_tmp_metadata")
    if metas
      hash[attr] = metas.map do |meta|
        {'id' => meta.id, 'key' => meta.key}
      end
    end
    hash
  end)).strip
end

#echo_uploads_data=(data) ⇒ Object

Pass in a hash that’s been encoded as JSON and then Base64.



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
# File 'lib/echo_uploads/model.rb', line 31

def echo_uploads_data=(data)
  parsed = JSON.parse Base64.decode64(data)
  # parsed will look like:
  # { 'attr1' => [ {'id' => 1, 'key' => 'abc...'} ] }
  unless parsed.is_a? Hash
    raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
  end
  parsed.each do |attr, attr_data|
    # If the :map option was passed, there may be multiple variants of the uploaded
    # file. Even if not, attr_data is still a one-element array.
    unless attr_data.is_a? Array
      raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
    end
    attr_data.each do |variant_data|
      unless variant_data.is_a? Hash
        raise ArgumentError, "Invalid JSON structure in: #{parsed.inspect}"
      end
      if meta = ::EchoUploads::File.where(
        id: variant_data['id'], key: variant_data['key'], temporary: true
      ).first
        if send("#{attr}_tmp_metadata").nil?
          send "#{attr}_tmp_metadata=", []
        end
        send("#{attr}_tmp_metadata") << meta
      end
    end
  end
end

#echo_uploads_map_metadata(attr, options) ⇒ Object

Helper method used internally by Echo Uploads.



61
62
63
64
# File 'lib/echo_uploads/model.rb', line 61

def (attr, options)
  meta = send("#{attr}_metadata")
  meta ? yield(meta) : nil
end