# frozen_string_literal: true # == Schema Information # # Table name: post_pastes # # id :bigint not null, primary key # file :text # file_name_cache :text # file_size_bytes :integer # orig_sha512_hash :text # sha512_hash :text # word_count :integer # created_at :datetime not null # updated_at :datetime not null # post_id :integer # # Indexes # # index_post_pastes_on_orig_sha512_hash (orig_sha512_hash) UNIQUE # index_post_pastes_on_sha512_hash (sha512_hash) UNIQUE # # Foreign Keys # # fk_rails_... (post_id => posts.id) # class Post::Paste < ActiveRecord::Base belongs_to :post, inverse_of: :paste belongs_to :thumbnail, class_name: 'Post', inverse_of: nil, optional: true # This is gross. # validates :orig_sha512_hash, uniqueness: true validates :file, presence: { unless: ->(image) { image.post&.destroyed_content? } } validates_with ImageHashDuplicationValidator, on: :create mount_uploader :file, TextUploader delegate :pretty_url, :url, to: :file after_commit do |paste| next if paste.post.disable_processing if paste.file.previously_changed? ProcessPasteJob.perform_later(paste.id) end end def auto_curated_tags [] end def file_name(truncated = false) return id.to_s if truncated return file_name_cache if file_name_cache # Not set? Let's build. # Trunate filename to 150 characters, making room for the path + filename on Windows - https://stackoverflow.com/questions/265769/maximum-filename-length-in-ntfs-windows-xp-and-windows-vista fn = "#{post.id}__#{Tag.where(id: post.tag_ids).display_order.pluck(:slug).join('_')}".gsub('%2F', '').delete('/')[0..150].sub(/%\h?\z/, '') rescue id.to_s update_columns(file_name_cache: fn) fn end def url(version = nil, hidden: false) file.url(version, hidden: hidden) end def as_indexed_json(*) { sha512_hash: sha512_hash, orig_sha512_hash: orig_sha512_hash, mime_type: 'text/plain', text: (body_reader.read rescue '') } end def body_reader fp = File.open(file.path) yield fp if block_given? fp end end