Search code examples
ruby-on-railsrubydelayed-jobfog

fog.io gem public_url returns two different urls


So here is my code. Looks like the typical fog code.

prefix = 'data:image/png;base64,'
png = Base64.decode64(data[prefix.length, data.length-1])

aws_settings = YAML.load_file(RAILS_ROOT + "/config/amazon_s3.yml")[RAILS_ENV] rescue nil
if aws_settings
  connection = Fog::Storage.new(
    :provider => 'AWS',
    :aws_access_key_id => aws_settings['access_key_id'],
    :aws_secret_access_key => aws_settings['secret_access_key']
  )

  directory = connection.directories.get(aws_settings['bucket_name'])

  filename = "#{quiz_id}/#{user_id}_#{question_id}.png"
  file = directory.files.create(
    :key => filename,
    :body => png,
    :public => true
  )
end

the problem is when I call file.public_url I will randomly get one of two different urls. Either I will get:

https://bucket_name.s3.amazonaws.com/19/235_146.png

or

http://s3.amazonaws.com/bucket_name/19/235_150.png

While I don't care one way or the other, I would like the url to be consistent.

Does anyone know how to remedy this issue? Am I doing something wrong in my code?

I should also mention that I'm doing this inside a Delayed::Job. It seems to always give me the https version when I do this as a normal method call. But when I stick it into Delayed Job is when I get the randomness. Very strange.


Solution

  • Wow, this is kind of embarrassing.. This has turned into a lesson about delayed jobs. Apparently it had cached my old code where I was hard coding the url string to store it off. Like this: url = "http://s3.amazonaws.com/bucket_name/{quiz_id}/{user_id}_{question_id}.png"

    I later changed it to this: url = file.public_url

    Fog does default to that string if your bucket name is not dns compliant. That is why I was so confused as to why this was happening. So yeah, just old cached code that was getting used. I shut down delayed jobs and started it back up again and problem be gone.

    The way I was able to figure it out was I was looking at the delayed jobs log and noticed it still has some old puts statements getting printed in there. That is when it clicked. :]