Sha256: a94bdad399698afda573671ff0c332b5f946a7c66e8690755f1ccc8e56d4d881

Contents?: true

Size: 1.4 KB

Versions: 6

Compression:

Stored size: 1.4 KB

Contents

# frozen_string_literal: true

module Shimmer
  module FileHelper
    extend ActiveSupport::Concern

    included do
      ActiveSupport.on_load(:action_view) do
        include Shimmer::FileAdditions
      end
    end
  end

  module FileAdditions
    def image_tag(source, **options)
      return nil if source.blank?

      if source.is_a?(ActiveStorage::Variant) || source.is_a?(ActiveStorage::Attached) || source.is_a?(ActiveStorage::Attachment) || source.is_a?(ActionText::Attachment)
        attachment = source
        width = options[:width]
        height = options[:height]
        source = image_file_path(source, width: width, height: height)
        options[:loading] = :lazy
        options[:srcset] = "#{source} 1x, #{image_file_path(attachment, width: width.to_i * 2, height: height ? height.to_i * 2 : nil)} 2x" if options[:width].present?
      end
      super source, options
    end

    def image_file_path(source, width: nil, height: nil)
      image_file_proxy(source, width: width, height: height)&.path
    end

    def image_file_url(source, width: nil, height: nil)
      image_file_proxy(source, width: width, height: height)&.url
    end

    def image_file_proxy(source, width: nil, height: nil)
      return if source.blank?
      return source if source.is_a?(String)

      blob = source.try(:blob) || source
      Shimmer::FileProxy.new(blob_id: blob.id, width: width, height: height)
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
shimmer-0.0.23 lib/shimmer/utils/file_helper.rb
shimmer-0.0.22 lib/shimmer/utils/file_helper.rb
shimmer-0.0.21 lib/shimmer/utils/file_helper.rb
shimmer-0.0.20 lib/shimmer/utils/file_helper.rb
shimmer-0.0.19 lib/shimmer/utils/file_helper.rb
shimmer-0.0.18 lib/shimmer/utils/file_helper.rb