Skip to content

Instantly share code, notes, and snippets.

@hoenth
Created April 15, 2015 12:22
Show Gist options
  • Save hoenth/960c9c00ae8acc2e88da to your computer and use it in GitHub Desktop.
Save hoenth/960c9c00ae8acc2e88da to your computer and use it in GitHub Desktop.
Cache file validator
class VerifyCachedFileValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if carrierwave_file_lost?(value.cache_dir, value.cache_name)
record.send("remove_#{attribute}!")
record.errors[attribute] << "We encountered an error when trying to upload your #{attribute}. Please select it again."
end
end
private
def carrierwave_file_lost?(cache_dir, cache_file_path)
cache_file_path.present? && !file_exists?(cache_dir, cache_file_path)
end
def file_exists?(cache_dir, cache_file_path)
File.exists?(File.join(Rails.root, 'public', cache_dir, cache_file_path))
end
end
@Nuru
Copy link

Nuru commented Oct 7, 2015

This code assumes you have configured CarrierWave's cache_dir to be relative to #{Rails.root}/public and fails otherwise, as would be the case on Heroku, for example. Replace line 17 with

    if cache_dir[0] == '/'
      File.exists?(File.join(cache_dir, cache_file_path))
    else
      File.exists?(File.join(Rails.root, 'public', cache_dir, cache_file_path))
    end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment