From 52b5ecb622aa77b49306f27d0138cce14e42591c Mon Sep 17 00:00:00 2001 From: Devin Howard Date: Mon, 23 Jan 2017 13:21:44 -0500 Subject: [PATCH] factor out a bunch of file types --- app/models/attachment.rb | 23 +++++++++++---- app/models/concerns/attachable.rb | 48 +++++++++++++++++++++++++++++++ app/models/topic.rb | 3 +- 3 files changed, 67 insertions(+), 7 deletions(-) create mode 100644 app/models/concerns/attachable.rb diff --git a/app/models/attachment.rb b/app/models/attachment.rb index 6db39fb4..52cf1a85 100644 --- a/app/models/attachment.rb +++ b/app/models/attachment.rb @@ -15,12 +15,25 @@ class Attachment < ApplicationRecord end } - validates_attachment_content_type :file, content_type: [ - %r{\Aimage/.*\Z}, - %r{\Avideo/.*\Z} - ] + validates_attachment_content_type :file, content_type: Attachable.allowed_types def image? - file.instance.file_content_type =~ /image/ + file.instance.file_content_type =~ %r{\Aimage} + end + + def audio? + file.instance.file_content_type ~= %r{\Aaudio} + end + + def text? + file.instance.file_content_type ~= %r{\Atext} + end + + def pdf? + file.instance.file_content_type == 'application/pdf' + end + + def document? + text? || pdf? end end diff --git a/app/models/concerns/attachable.rb b/app/models/concerns/attachable.rb new file mode 100644 index 00000000..49f8b993 --- /dev/null +++ b/app/models/concerns/attachable.rb @@ -0,0 +1,48 @@ +# frozen_string_literal: true +module Attachable + extend ActiveSupport::Concern + + has_many :attachments, as: :attachable, dependent: :destroy + + def images + attachments.where(file_content_type: self.image_types) + end + + def audios + attachments.where(file_content_type: self.audio_types) + end + + def texts + attachments.where(file_content_type: self.text_types) + end + + def pdfs + attachments.where(file_content_type: self.pdf_types) + end + + def documents + attachments.where(file_content_type: self.text_types + self.pdf_types) + end + + class << self + def image_types + ['image/png', 'image/gif', 'image/jpeg'] + end + + def audio_types + ['audio/ogg', 'audio/mp3'] + end + + def text_types + ['text/plain', 'text/markdown'] + end + + def pdf_types + ['application/pdf'] + end + + def allowed_types + image_types + audio_types + text_types + pdf_types + end + end +end diff --git a/app/models/topic.rb b/app/models/topic.rb index 5b628d8b..2a8cbc46 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true class Topic < ApplicationRecord include TopicsHelper + include Attachable belongs_to :user belongs_to :defer_to_map, class_name: 'Map', foreign_key: 'defer_to_map_id' @@ -21,8 +22,6 @@ class Topic < ApplicationRecord validates :permission, presence: true validates :permission, inclusion: { in: Perm::ISSIONS.map(&:to_s) } - has_many :attachments, as: :attachable, dependent: :destroy - def synapses synapses1.or(synapses2) end