1
0

site_upload.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. FAVICON_SIZES = [16, 32, 48].freeze
  20. APPLE_ICON_SIZES = [57, 60, 72, 76, 114, 120, 144, 152, 167, 180, 1024].freeze
  21. ANDROID_ICON_SIZES = [36, 48, 72, 96, 144, 192, 256, 384, 512].freeze
  22. APP_ICON_SIZES = (APPLE_ICON_SIZES + ANDROID_ICON_SIZES).uniq.freeze
  23. STYLES = {
  24. app_icon:
  25. APP_ICON_SIZES.to_h do |size|
  26. [:"#{size}", { format: 'png', geometry: "#{size}x#{size}#", file_geometry_parser: FastGeometryParser }]
  27. end.freeze,
  28. favicon:
  29. FAVICON_SIZES.to_h do |size|
  30. [:"#{size}", { format: 'png', geometry: "#{size}x#{size}#", file_geometry_parser: FastGeometryParser }]
  31. end.freeze,
  32. thumbnail: {
  33. '@1x': {
  34. format: 'png',
  35. geometry: '1200x630#',
  36. file_geometry_parser: FastGeometryParser,
  37. blurhash: {
  38. x_comp: 4,
  39. y_comp: 4,
  40. }.freeze,
  41. },
  42. '@2x': {
  43. format: 'png',
  44. geometry: '2400x1260#',
  45. file_geometry_parser: FastGeometryParser,
  46. }.freeze,
  47. }.freeze,
  48. mascot: {}.freeze,
  49. }.freeze
  50. has_attached_file :file, styles: ->(file) { STYLES[file.instance.var.to_sym] }, convert_options: { all: '-coalesce +profile "!icc,*" +set date:modify +set date:create +set date:timestamp' }, processors: [:lazy_thumbnail, :blurhash_transcoder, :type_corrector]
  51. validates_attachment_content_type :file, content_type: %r{\Aimage/.*\z}
  52. validates :file, presence: true
  53. validates :var, presence: true, uniqueness: true
  54. before_save :set_meta
  55. after_commit :clear_cache
  56. def cache_key
  57. "site_uploads/#{var}"
  58. end
  59. private
  60. def set_meta
  61. tempfile = file.queued_for_write[:original]
  62. return if tempfile.nil?
  63. width, height = FastImage.size(tempfile.path)
  64. self.meta = { width: width, height: height }
  65. end
  66. def clear_cache
  67. Rails.cache.delete(cache_key)
  68. end
  69. end