site_upload.rb 1015 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 :var, presence: true, uniqueness: true
  20. before_save :set_meta
  21. after_commit :clear_cache
  22. def cache_key
  23. "site_uploads/#{var}"
  24. end
  25. private
  26. def set_meta
  27. tempfile = file.queued_for_write[:original]
  28. return if tempfile.nil?
  29. width, height = FastImage.size(tempfile.path)
  30. self.meta = { width: width, height: height }
  31. end
  32. def clear_cache
  33. Rails.cache.delete(cache_key)
  34. end
  35. end