Class: S3DirectUpload::UploadHelper::S3Uploader

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

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ S3Uploader

Returns a new instance of S3Uploader.



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/s3_direct_upload/form_helper.rb', line 13

def initialize(options)
  @options = options.reverse_merge(
    id: "fileupload",
    aws_access_key_id: S3DirectUpload.config.access_key_id,
    aws_secret_access_key: S3DirectUpload.config.secret_access_key,
    bucket: S3DirectUpload.config.bucket,
    acl: "public-read",
    expiration: 10.hours.from_now,
    max_file_size: 500.megabytes,
    as: "file"
  )
end

Instance Method Details

#fieldsObject



39
40
41
42
43
44
45
46
47
# File 'lib/s3_direct_upload/form_helper.rb', line 39

def fields
  {
    :key => key,
    :acl => @options[:acl],
    :policy => policy,
    :signature => signature,
    "AWSAccessKeyId" => @options[:aws_access_key_id],
  }
end

#form_optionsObject



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/s3_direct_upload/form_helper.rb', line 26

def form_options
  {
    id: @options[:id],
    method: "post",
    authenticity_token: false,
    multipart: true,
    data: {
      post: @options[:post],
      as: @options[:as]
    }
  }
end

#keyObject



49
50
51
# File 'lib/s3_direct_upload/form_helper.rb', line 49

def key
  @key ||= "uploads/#{SecureRandom.hex}/${filename}"
end

#policyObject



57
58
59
# File 'lib/s3_direct_upload/form_helper.rb', line 57

def policy
  Base64.encode64(policy_data.to_json).gsub("\n", "")
end

#policy_dataObject



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/s3_direct_upload/form_helper.rb', line 61

def policy_data
  {
    expiration: @options[:expiration],
    conditions: [
      ["starts-with", "$utf8", ""],
      ["starts-with", "$key", ""],
      ["content-length-range", 0, @options[:max_file_size]],
      {bucket: @options[:bucket]},
      {acl: @options[:acl]}
    ]
  }
end

#signatureObject



74
75
76
77
78
79
80
81
# File 'lib/s3_direct_upload/form_helper.rb', line 74

def signature
  Base64.encode64(
    OpenSSL::HMAC.digest(
      OpenSSL::Digest::Digest.new('sha1'),
      @options[:aws_secret_access_key], policy
    )
  ).gsub("\n", "")
end

#urlObject



53
54
55
# File 'lib/s3_direct_upload/form_helper.rb', line 53

def url
  "https://#{@options[:bucket]}.s3.amazonaws.com/"
end