app/models/cas/media_file.rb in cas-cms-1.0.0.alpha1 vs app/models/cas/media_file.rb in cas-cms-1.0.0.alpha2
- old
+ new
@@ -1,14 +1,14 @@
module Cas
class MediaFile < ApplicationRecord
- include FileUploader::Attachment.new(:file)
+ include FileUploader::Attachment.new(:file) # This is for the Shrine gem
class UnknownPath < StandardError; end
class UnknownFileService < StandardError; end
- belongs_to :attachable, polymorphic: true
- belongs_to :author, class_name: "::Cas::User"
+ belongs_to :attachable, polymorphic: true, optional: true
+ belongs_to :author, class_name: "::Cas::User", optional: true
before_validation :set_media_type
before_save :set_image_as_unique_cover
scope :cover, ->{ where(cover: true) }
@@ -37,16 +37,40 @@
[host, path].join("/").gsub(/([^:])\/\//, '\1/')
else
raise UnknownFileService
end
- # Shrine gem uses `file_data`
+ # Shrine gem uses `file_data` because `file` is the name we specified for
+ # the Attachment at the top of this model.
elsif JSON.parse(file_data).present?
- if cdn.present?
- file_url(version.to_sym, host: cdn, public: true)
- else
- file_url(version.to_sym, public: true).gsub(/\?.*/, "")
- end
+ params = {
+ public: true
+ }
+ params[:host] = cdn if cdn.present?
+
+ # With Shrine, the default image version is :original. Other versions
+ # are called derivatives. The `file_url` method expects a derivative
+ # name as first argument.
+ #
+ # When we pass :original, it just returns `nil` because the main file is
+ # not considered a derivative. If we had something like :larger, then
+ # that would be the argument.
+ url = if version.to_sym == :original
+ file_url(params)
+ else
+ file_url(version, params)
+ end
+
+ # Shrine 3 returns `nil` when a derivative doesn't exist. It also
+ # returns `nil` when we pass parameters. This is a fallback way of
+ # avoiding any `nil` returns. However, notice that we can't pass
+ # `params` because Shrine just ignores it and returns `nil` if it's
+ # present (it wasn't like that in Shrine 2).
+ url = file_url if url.blank?
+
+ # Amazon S3 has URLs that include some query strings like signatures
+ # which we don't want to include in URLs.
+ url&.gsub(/\?.*/, "")
else
raise UnknownPath
end
end