Module: S3Uploader::S3Attachment::ClassMethods

Defined in:
app/s3_uploader/lib/s3_attachment.rb

Instance Method Summary collapse

Instance Method Details

#attachment(name, bucket) ⇒ Object



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
# File 'app/s3_uploader/lib/s3_attachment.rb', line 7

def attachment(name, bucket)
  unless RUBY_PLATFORM == 'opal'
    # Create the bucket and set the CORS policy if needed
    Volt.current_app.once('post_boot') do
      S3BucketManager.ensure_bucket(bucket)
    end
  end

  url_field_name = :"#{name}_url"
  field(url_field_name, String)

  upload_percent_field_name = :"#{name}_upload_percent"
  reactive_accessor(upload_percent_field_name)

  promise_field_name = :"#{name}_uploading_promise"
  attr_accessor(promise_field_name)

  # Create a method that returns the bucket passed in
  define_method(:"#{name}_bucket") do
    bucket
  end

  unless RUBY_PLATFORM == 'opal'
    s3 = Volt.config.s3
    current_buckets = (s3 ? s3.to_h[:buckets] : nil) || []
    current_buckets << bucket

    Volt.configure do |config|
      config.s3.buckets = current_buckets
    end
  end

  # An aggrate method is created for assigning to the value="{{ name }}"
  # property of the tag.
  define_method(name) do
    url = send(url_field_name)
    upload_percent = send(upload_percent_field_name)
    [url, upload_percent]
  end

  define_method(:"#{name}=") do |val|
    send(:"#{upload_percent_field_name}=", val[0])
    send(:"#{url_field_name}=", val[1])
    send(:"#{promise_field_name}=", val[2])
  end

  validate do
    # MainController (linked via the value attribute on the s3-upload tag)
    # will set a promise, which it resolves when the file is upload (if it
    # is uploading).
    promise = send(promise_field_name)

    if promise.is_a?(Promise) && !promise.realized?
      promise = promise.then do
        puts "Uploaded"
        trigger!("uploaded_#{name}")
      end
    end

    # return the promise
    promise
  end
end