1
0

site_upload.rb 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. # blurhash :string
  16. #
  17. class SiteUpload < ApplicationRecord
  18. include Attachmentable
  19. STYLES = {
  20. thumbnail: {
  21. '@1x': {
  22. format: 'png',
  23. geometry: '1200x630#',
  24. file_geometry_parser: FastGeometryParser,
  25. blurhash: {
  26. x_comp: 4,
  27. y_comp: 4,
  28. }.freeze,
  29. },
  30. '@2x': {
  31. format: 'png',
  32. geometry: '2400x1260#',
  33. file_geometry_parser: FastGeometryParser,
  34. }.freeze,
  35. }.freeze,
  36. mascot: {}.freeze,
  37. }.freeze
  38. has_attached_file :file, styles: ->(file) { STYLES[file.instance.var.to_sym] }, convert_options: { all: '-coalesce +profile "!icc,*" +set modify-date +set create-date' }, processors: [:lazy_thumbnail, :blurhash_transcoder, :type_corrector]
  39. validates_attachment_content_type :file, content_type: %r{\Aimage/.*\z}
  40. validates :file, presence: true
  41. validates :var, presence: true, uniqueness: true
  42. before_save :set_meta
  43. after_commit :clear_cache
  44. def cache_key
  45. "site_uploads/#{var}"
  46. end
  47. private
  48. def set_meta
  49. tempfile = file.queued_for_write[:original]
  50. return if tempfile.nil?
  51. width, height = FastImage.size(tempfile.path)
  52. self.meta = { width: width, height: height }
  53. end
  54. def clear_cache
  55. Rails.cache.delete(cache_key)
  56. end
  57. end