AWS::S3::S3Object.url_for - How to do this with the new AWS SDK Gem? AWS::S3::S3Object.url_for - How to do this with the new AWS SDK Gem? ruby-on-rails ruby-on-rails

AWS::S3::S3Object.url_for - How to do this with the new AWS SDK Gem?


To generate a url using the aws-sdk gem you should use the AWS::S3Object#url_for method.
You can access the S3Object instance from a paperclip attachment using #s3_object. The snippet below should resolve your issue.

def authenticated_url(style = nil, expires_in = 90.minutes)  attachment.s3_object(style).url_for(:read, :secure => true, :expires => expires_in).to_send


Recently I upgraded to the newest gem for AWS SDK 2 for Ruby (aws-sdk-2.1.13) and getting pre-signed url has changed in this SDK version.

The way of getting it:

presigner = Aws::S3::Presigner.newpresigner.presigned_url(:get_object, #method                        bucket: 'bucket-name', #name of the bucket                        key: "key-name", #key name                        expires_in: 7.days.to_i #time should be in seconds                        ).to_s

You can find more info here:http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Presigner.html


After looking into the documentation, url_for is an instance method and not a class method.

To generate a URL with aws-sdk, you need to do the following:

bucket = AWS::S3::Bucket.new(attachment.bucket_name)s3object = AWS::S3::S3Object.new(bucket, attachment.path(style || attachment.default_style))s3object.url_for(:read, :expires => expires_in)

The options are slightly different than the ones you specified.

Options Hash (options):

:expires (Object) — Sets the expiration time of the URL; after this time S3 will return an error if the URL is used. This can be an integer (to specify the number of seconds after the current time), a string (which is parsed as a date using Time#parse), a Time, or a DateTime object. This option defaults to one hour after the current time.

:secure (String) — Whether to generate a secure (HTTPS) URL or a plain HTTP url.

:response_content_type (String) — Sets the Content-Type header of the response when performing an HTTP GET on the returned URL.

:response_content_language (String) — Sets the Content-Language header of the response when performing an HTTP GET on the returned URL.

:response_expires (String) — Sets the Expires header of the response when performing an HTTP GET on the returned URL.

:response_cache_control (String) — Sets the Cache-Control header of the response when performing an HTTP GET on the returned URL.

:response_content_disposition (String) — Sets the Content-Disposition header of the response when performing an HTTP GET on the returned URL.

:response_content_encoding (String) — Sets the Content-Encoding header of the response when performing an HTTP GET on the returned URL.