Created
April 15, 2015 12:22
-
-
Save hoenth/960c9c00ae8acc2e88da to your computer and use it in GitHub Desktop.
Cache file validator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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