Skip to content

Instantly share code, notes, and snippets.

@julianrubisch
Created January 13, 2019 18:09
Show Gist options
  • Save julianrubisch/85199e4bea13e0edfc86cca074fad6a7 to your computer and use it in GitHub Desktop.
Save julianrubisch/85199e4bea13e0edfc86cca074fad6a7 to your computer and use it in GitHub Desktop.
Previewable, first try
module ActiveStoragePreviewable
extend ActiveSupport::Concern
included do
attachments = reflect_on_all_associations.select do |assoc|
assoc.klass == ActiveStorage::Attachment
end
attachments.each do |att|
prefix = (/(.*)_attachment\Z/.match att.name.to_s)[1]
method_name = att.name.to_s.gsub(/_attachment/, '_shim')
define_method(method_name.to_sym) do
public_send(prefix).attached? ? public_send(prefix) : NullAttachment.new
end
end
end
end
class NullAttachment
attr_reader :blob
Blob = Struct.new(:content_type)
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment