Class: Upyun::Form

Inherits:
Object
  • Object
show all
Includes:
Utils
Defined in:
lib/upyun/form.rb

Constant Summary collapse

VALID_PARAMS =
%w(
  bucket
  save-key
  expiration
  allow-file-type
  content-length-range
  content-md5
  content-secret
  content-type
  image-width-range
  image-height-range
  notify-url
  return-url
  x-gmkerl-thumbnail
  x-gmkerl-type
  x-gmkerl-value
  x-gmkerl-quality
  x-gmkerl-unsharp
  x-gmkerl-rotate
  x-gmkerl-crop
  x-gmkerl-exif-switch
  ext-param
)

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Utils

included, #md5

Constructor Details

#initialize(password, bucket, options = {timeout: 60}) ⇒ Form

Returns a new instance of Form.



38
39
40
41
42
43
# File 'lib/upyun/form.rb', line 38

def initialize(password, bucket, options={timeout: 60})
  @password = password
  @bucket = bucket
  @options = options
  @endpoint = ED_AUTO
end

Instance Attribute Details

#bucketObject

Returns the value of attribute bucket.



35
36
37
# File 'lib/upyun/form.rb', line 35

def bucket
  @bucket
end

#optionsObject (readonly)

Returns the value of attribute options.



36
37
38
# File 'lib/upyun/form.rb', line 36

def options
  @options
end

#passwordObject

Returns the value of attribute password.



35
36
37
# File 'lib/upyun/form.rb', line 35

def password
  @password
end

Instance Method Details

#upload(file, opts = {}) ⇒ Object



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
73
74
75
76
77
78
79
80
81
82
# File 'lib/upyun/form.rb', line 45

def upload(file, opts={})
  base_opts = HashWithIndifferentAccess.new({
    'bucket' => @bucket,
    'save-key' => '/{year}/{mon}/{day}/{filename}{.suffix}',
    'expiration' => Time.now.to_i + 600
  })

  payload = {
    policy: policy(base_opts.merge(opts)),
    signature: signature,
    file: file.is_a?(File) ? file : File.new(file, 'rb')
  }

  rest_client.post(payload, {'User-Agent' => "Upyun-Ruby-SDK-#{VERSION}"}) do |res|
    case res.code
    when 302

      # return 302 when set 'return-url' in opts
      hds = res.headers
      body = CGI::parse(URI.parse(hds[:location]).query).reduce({}) do |memo, (k, v)|
        memo.merge!({k.to_sym => v.first})
      end

      body[:code] = body[:code].to_i
      body[:time] = body[:time].to_i
      body[:request_id] = hds[:x_request_id]
      body
    else
      body = JSON.parse(res.body, symbolize_names: true)

      # TODO Upyun have a small bug for the `code`,
      # we have to adjust it to integer
      body[:code] = body[:code].to_i
      body[:request_id] = res.headers[:x_request_id]
      body
    end
  end
end