Skip to content

Instantly share code, notes, and snippets.

@ericboehs
Last active September 7, 2019 20:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericboehs/a8c93da8c22306b6e48aa941c99d2f34 to your computer and use it in GitHub Desktop.
Save ericboehs/a8c93da8c22306b6e48aa941c99d2f34 to your computer and use it in GitHub Desktop.
Helper method to get the URL to an ActiveStorage Blob/Variant
# frozen_string_literal: true
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def attached_url_for(attached, variant: nil, cloudfront_endpoint: ENV['CLOUDFRONT_ENDPOINT'], fallback_url: nil)
if attached.attached?
attached = attached.variant variant if variant
path_helper = Rails.application.routes.url_helpers.method :rails_blob_path
if cloudfront_endpoint
path_helper = Rails.application.routes.url_helpers.method :rails_representation_path if variant
URI.join(cloudfront_endpoint, path_helper[attached]).to_s
else
Rails.application.routes.url_helpers.url_for attached
end
else
fallback_url || ActionController::Base.helpers.image_url('default-organization-logo.gif')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment