saving a gravatar to activeStorage

45 views Asked by At

the following cUrl command in the console, as per gravatar instructions saves an image to the directory it is being called from

curl "https://www.gravatar.com/avatar/ZUETpSoXKBP5VXW4qQnQFIZcLpxh5Ix2?d=identicon" --output 'temp_avatar'

However, in order to avoid hitting their server, the goal is to have an action save the output via ActiveStorage

class UserPreference < ApplicationRecord
  has_one_attached :identicon

and the controller action

    if !current_user.user_preference.identicon.present?
      puts 'identicon absent'
      result = Net::HTTP.get_response(URI.parse("https://www.gravatar.com/avatar/#{current_user.virtual_qr_code}.jpg?d=identicon --output '#{current_user.id}_avatar' "))
      puts result.inspect
       current_user.user_preference.identicon.attach(result)

the result is a bit perplexing. The puts commands get a response, but a different one from the processing of cUrl straight out

identicon absent
#<Net::HTTPFound 302 Found readbody=true>

Could not find or build blob: expected attachable, got #<Net::HTTPFound 302 Found readbody=true>

What is mistaken in expecting the image output to be different when called via Net::HTTP?
How should this be called to save via ActiveStorage?

1

There are 1 answers

4
Frederik Spang On

It looks like you've included some of the CURL command into the URL of the Net::HTTP call, and are trying to call this string as an URL "https://www.gravatar.com/avatar/#{current_user.virtual_qr_code}.jpg?d=identicon --output '#{current_user.id}_avatar' " where you actually wanted: "https://www.gravatar.com/avatar/#{current_user.virtual_qr_code}.jpg?d=identicon"

You cannot use --output from within the URL, but you should use the returned body of the GET request instead.

    if !current_user.user_preference.identicon.present?
      puts 'identicon absent'
      result = Net::HTTP.get_response(URI.parse("https://www.gravatar.com/avatar/#{current_user.virtual_qr_code}.jpg?d=identicon"))
      puts result.inspect #=> Net::HTTPResponse object

      # result.body will return the actual content of the HTTP request, instead of the Net::HTTPResponse object.
      current_user.user_preference.identicon.attach(result.body)