2012-02-04 22 views
21

He estado usando esto para siempre con el clip y AWS-s3:AWS :: S3 :: S3Object.url_for - ¿Cómo hacer esto con la nueva AWS SDK Gem?

def authenticated_url(style = nil, expires_in = 90.minutes) 
     AWS::S3::S3Object.url_for(attachment.path(style || attachment.default_style), attachment.bucket_name, :expires_in => expires_in, :use_ssl => true) 
    end 

El nuevo clip utiliza la gema-AWS SDK, que rompe esta dando el error:

undefined method `url_for' for AWS::S3:Class 

Alguien sabe cómo hacer que este método funcione con la nueva gema AWS-SDK?

Respuesta

29

generar una URL utilizando la gema-AWS SDK se debe utilizar el método de AWS::S3Object#url_for.
Puede acceder a la instancia de S3Object desde un archivo adjunto de clip usando # s3_object. El siguiente fragmento debería resolver su problema.

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

S3Object # url_for devuelve un objeto URI :: HTTPS. Si lo prefiere, puede omitir los #to_s de la cadena de métodos. –

+0

AWS :: S3 :: Base es una clase dentro de la antigua gema aws-s3, pero no existe como parte de la gema aws-sdk. Ambas gemas definen la clase AWS :: S3 sin embargo. Examiné el rastro de la pila y descubro qué hace referencia a AWS :: S3 :: Base. –

5

Después de buscar en el documentation, url_for es un método de instancia y no un método de clase.

Para generar una URL con AWS-SDK, que tiene que hacer lo siguiente:

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) 

Las opciones son ligeramente diferentes a las especificadas.

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.

+0

"editar en las confirmaciones"? Entonces, ¿cómo debería generar una URL con la gema aws-sdk? – AnApprentice

+0

@AnApprentice Ver mi edición. Además, ¿para qué versión de la gema funcionó su método? – Gazler

+0

@AnApprentice He editado de nuevo para reflejar su código de muestra. – Gazler

3

recientemente he hecho el cambio de AWS-s3 a AWS-SDK también. He sustituido toda mi url_for con lo siguiente:

def authenticated_url(style = nil, expires_in = 90.minutes) 
    self.attachment.expiring_url(expires_in, (style || attachment.default_style)) 
end 

Se puede ver la discusión de las cuestiones paperclip hilo aquí: https://github.com/thoughtbot/paperclip/issues/732

+0

Que aún errores – AnApprentice

+0

Mire la definición del método aquí: https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/storage/s3.rb. Es lo mismo que tu respuesta aceptada. La única razón por la que podría ver que no funciona es si no tiene un archivo s3.yml con su clave de acceso y clave secreta o si no está especificando s3 en las opciones del clip. ¿Qué error estás recibiendo? – John

9

Recientemente he actualizado a la nueva joya para AWS SDK 2 para Ruby (AWS-SDK -2.1.13) y la modificación de la url pre-firmada ha cambiado en esta versión del SDK.

La manera de conseguirlo:

presigner = Aws::S3::Presigner.new 
presigner.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 

Puede encontrar más información aquí: http://docs.aws.amazon.com/sdkforruby/api/Aws/S3/Presigner.html

+1

Encontré que un Aws :: S3 :: ObjectSummary también responde a 'presigned_url', y no necesitaba un objeto Aws :: S3 :: Presigner. Los detalles en los comentarios son de oro, gracias. – pdobb

Cuestiones relacionadas