'Use existing image on S3 if it exists from Rails seeds

I am trying to improve a set of Rails seeds which currently upload all their file attachments to S3 regardless of whether they currently exist. This results in very slow seeds and an obvious wastage of S3 resources. It looks like this:

factory :logo_attachment do
  file do
    filename = Dir.glob(Rails.root.join('test', 'fixtures', 'files','logos','*.{jpg,png,gif,svg}')).sample
    extname = File.extname(filename)[1..-1]
    mime_type = Mime::Type.lookup_by_extension(extname)
    content_type = mime_type.to_s
    fixture_file_upload(filename, content_type)
  end
end

Attached with:

after(:create) do |organisation|
  organisation.logo = create(:logo_attachment, attacher: organisation)
end

How can I improve this state of affairs so it uses pre-existing images on S3? I did wish to use local images only for this process but the application is heavily tied to S3.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source