site_upload.rb 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: site_uploads
  5. #
  6. # id :bigint(8) not null, primary key
  7. # var :string default(""), not null
  8. # file_file_name :string
  9. # file_content_type :string
  10. # file_file_size :integer
  11. # file_updated_at :datetime
  12. # meta :json
  13. # created_at :datetime not null
  14. # updated_at :datetime not null
  15. #
  16. class SiteUpload < ApplicationRecord
  17. has_attached_file :file
  18. validates_attachment_content_type :file, content_type: /\Aimage\/.*\z/
  19. validates :file, presence: true
  20. validates :var, presence: true, uniqueness: true
  21. before_save :set_meta
  22. after_commit :clear_cache
  23. def cache_key
  24. "site_uploads/#{var}"
  25. end
  26. private
  27. def set_meta
  28. tempfile = file.queued_for_write[:original]
  29. return if tempfile.nil?
  30. width, height = FastImage.size(tempfile.path)
  31. self.meta = { width: width, height: height }
  32. end
  33. def clear_cache
  34. Rails.cache.delete(cache_key)
  35. end
  36. end