preview_card.rb 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # frozen_string_literal: true
  2. # == Schema Information
  3. #
  4. # Table name: preview_cards
  5. #
  6. # id :bigint(8) not null, primary key
  7. # url :string default(""), not null
  8. # title :string default(""), not null
  9. # description :string default(""), not null
  10. # image_file_name :string
  11. # image_content_type :string
  12. # image_file_size :integer
  13. # image_updated_at :datetime
  14. # type :integer default("link"), not null
  15. # html :text default(""), not null
  16. # author_name :string default(""), not null
  17. # author_url :string default(""), not null
  18. # provider_name :string default(""), not null
  19. # provider_url :string default(""), not null
  20. # width :integer default(0), not null
  21. # height :integer default(0), not null
  22. # created_at :datetime not null
  23. # updated_at :datetime not null
  24. # embed_url :string default(""), not null
  25. #
  26. class PreviewCard < ApplicationRecord
  27. IMAGE_MIME_TYPES = ['image/jpeg', 'image/png', 'image/gif'].freeze
  28. LIMIT = 1.megabytes
  29. self.inheritance_column = false
  30. enum type: [:link, :photo, :video, :rich]
  31. has_and_belongs_to_many :statuses
  32. has_attached_file :image, styles: ->(f) { image_styles(f) }, convert_options: { all: '-quality 80 -strip' }
  33. include Attachmentable
  34. validates :url, presence: true, uniqueness: true
  35. validates_attachment_content_type :image, content_type: IMAGE_MIME_TYPES
  36. validates_attachment_size :image, less_than: LIMIT
  37. remotable_attachment :image, LIMIT
  38. scope :cached, -> { where.not(image_file_name: [nil, '']) }
  39. before_save :extract_dimensions, if: :link?
  40. def missing_image?
  41. width.present? && height.present? && image_file_name.blank?
  42. end
  43. def save_with_optional_image!
  44. save!
  45. rescue ActiveRecord::RecordInvalid
  46. self.image = nil
  47. save!
  48. end
  49. class << self
  50. private
  51. def image_styles(f)
  52. styles = {
  53. original: {
  54. geometry: '400x400>',
  55. file_geometry_parser: FastGeometryParser,
  56. convert_options: '-coalesce -strip',
  57. },
  58. }
  59. styles[:original][:format] = 'jpg' if f.instance.image_content_type == 'image/gif'
  60. styles
  61. end
  62. end
  63. private
  64. def extract_dimensions
  65. file = image.queued_for_write[:original]
  66. return if file.nil?
  67. width, height = FastImage.size(file.path)
  68. return nil if width.nil?
  69. self.width = width
  70. self.height = height
  71. end
  72. end