Sha256: 3d3228ced82ebe2a90e339fad4276ecafd0e122897aaebc017596dcf4e16b12b

Contents?: true

Size: 1.53 KB

Versions: 16

Compression:

Stored size: 1.53 KB

Contents

# frozen_string_literal: true

class Attachment < ApplicationRecord
  include Dis::Model
  include PagesCore::Sweepable

  belongs_to :user, optional: true

  validates_data_presence
  validates :content_type, presence: true
  validates :filename, presence: true
  validates :content_length, presence: true

  localizable do
    attribute :name
    attribute :description
  end

  before_validation :set_name_from_filename

  class << self
    def verifier
      @verifier ||= PagesCore::DigestVerifier.new(
        Rails.application.key_generator.generate_key("attachments")
      )
    end

    def formats
      {
        "audio/mpeg" => :mp3,
        "image/gif" => :gif,
        "image/jpeg" => :jpg,
        "image/jpg" => :jpg,
        "image/pjpeg" => :jpg,
        "image/png" => :png,
        "application/pdf" => :pdf
      }
    end
  end

  def digest
    return unless id

    self.class.verifier.generate(id.to_s)
  end

  def format?
    content_type && self.class.formats.key?(content_type)
  end

  def format
    self.class.formats[content_type]
  end

  def filename_extension
    if filename_extension?
      filename.match(/\.([^.]+)$/)[1]
    else
      ""
    end
  end

  def filename_extension?
    filename =~ /\./
  end

  # Includes a timestamp fingerprint in the URL param, so
  # that rendered images can be cached indefinitely.
  def to_param
    [id, updated_at.utc.to_fs(cache_timestamp_format)].join("-")
  end

  private

  def set_name_from_filename
    self.name ||= File.basename(filename, ".*") if filename? && locale
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
pages_core-3.14.0 app/models/attachment.rb
pages_core-3.13.0 app/models/attachment.rb
pages_core-3.12.7 app/models/attachment.rb
pages_core-3.12.6 app/models/attachment.rb
pages_core-3.12.5 app/models/attachment.rb
pages_core-3.12.4 app/models/attachment.rb
pages_core-3.12.3 app/models/attachment.rb
pages_core-3.12.2 app/models/attachment.rb
pages_core-3.12.1 app/models/attachment.rb
pages_core-3.12.0 app/models/attachment.rb
pages_core-3.11.3 app/models/attachment.rb
pages_core-3.11.2 app/models/attachment.rb
pages_core-3.11.1 app/models/attachment.rb
pages_core-3.11.0 app/models/attachment.rb
pages_core-3.10.2 app/models/attachment.rb
pages_core-3.10.1 app/models/attachment.rb