Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Last active January 1, 2019 13:20
Show Gist options
  • Save julianrubisch/1fbe3ff915e9a5407be5839958925059 to your computer and use it in GitHub Desktop.
Save julianrubisch/1fbe3ff915e9a5407be5839958925059 to your computer and use it in GitHub Desktop.
ActiveStorage NullAttachment
- if file.blob.image?
= image_tag file.variant(resize: "512x512"), class: 'img-thumbnail w-25 float-left mr-3'
- elsif file.blob.content_type =~ /pdf/
= image_tag file.preview(resize: "512x512"), class: 'img-thumbnail w-25 float-left mr-3'
module ActiveStoragePreviewable
extend ActiveSupport::Concern
included do
def method_missing(method_name, *args, &block)
if /(.*)_shim\Z/.match?(method_name)
public_send(prefix(method_name)).attached? ? public_send(prefix(method_name)) : NullAttachment.new
else
super
end
end
def respond_to_missing?(method_name, include_private = false)
if /(.*)_shim\Z/.match?(method_name)
attachments = reflect_on_all_associations.select do |assoc|
assoc.klass == ActiveStorage::Attachment
end
attachments.map(&:name).map(&:to_s).include? "#{prefix(method_name)}_attachment"
else
super(method_name, include_private)
end
end
private
def prefix(method_name)
(/(.*)_shim\Z/.match method_name.id2name)[1]
end
end
end
class NullAttachment
attr_reader :blob
Blob = Struct.new(:content_type) do
def image?
content_type.start_with?("image")
end
end
def initialize(content_type: 'image')
@blob = Blob.new(content_type)
end
def variant(resize:)
"http://placehold.it/#{resize}"
end
def preview(resize:)
"http://placehold.it/#{resize}"
end
end
= render partial: 'common/active_storage_preview', locals: { file: @user.profile_picture_shim }
class User < ApplicationRecord
include ActiveStoragePreviewable
has_one_attached :profile_picture
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment