aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorDavid Heinemeier Hansson <david@loudthinking.com>2017-07-28 15:27:43 -0500
committerDavid Heinemeier Hansson <david@loudthinking.com>2017-07-28 15:27:43 -0500
commit801b4eb465cd48435abddac881b92c93470b6933 (patch)
tree63b96f17c29a25807da725b23b7f2706b3d2b877
parent696b8c6f43214ed4b9b79f36a9f68de0db19f1ee (diff)
downloadrails-801b4eb465cd48435abddac881b92c93470b6933.tar.gz
rails-801b4eb465cd48435abddac881b92c93470b6933.tar.bz2
rails-801b4eb465cd48435abddac881b92c93470b6933.zip
Add Blob#type as a StringInquirer
-rw-r--r--app/models/active_storage/blob.rb14
-rw-r--r--test/models/blob_test.rb6
2 files changed, 20 insertions, 0 deletions
diff --git a/app/models/active_storage/blob.rb b/app/models/active_storage/blob.rb
index 6a7836b9e5..b2d5b2362c 100644
--- a/app/models/active_storage/blob.rb
+++ b/app/models/active_storage/blob.rb
@@ -84,6 +84,20 @@ class ActiveStorage::Blob < ActiveRecord::Base
ActiveStorage::Filename.new(self[:filename])
end
+ # Returns a `StringInquirer` based on the content_type that is broken into text, image, audio, video, pdf, or,
+ # the catch-all, file. Example: `messages.attachments.select(&:image?)`.
+ def type
+ @type ||=
+ case content_type
+ when /^text/ then 'text'
+ when /^image/ then 'image'
+ when /^audio/ then 'audio'
+ when /^video/ then 'video'
+ when /pdf/ then 'pdf'
+ else 'file'
+ end.inquiry
+ end
+
# Returns a `ActiveStorage::Variant` instance with the set of `transformations` passed in. This is only relevant
# for image files, and it allows any image to be transformed for size, colors, and the like. Example:
#
diff --git a/test/models/blob_test.rb b/test/models/blob_test.rb
index a5b291d5db..b51be7a93b 100644
--- a/test/models/blob_test.rb
+++ b/test/models/blob_test.rb
@@ -11,6 +11,12 @@ class ActiveStorage::BlobTest < ActiveSupport::TestCase
assert_equal Digest::MD5.base64digest(data), blob.checksum
end
+ test "inquery type" do
+ blob = create_blob data: "Hello world!"
+ assert blob.type.text?
+ assert_not blob.type.audio?
+ end
+
test "download yields chunks" do
blob = create_blob data: "a" * 75.kilobytes
chunks = []