Sha256: e2ec4af40e5fa7c124e1bb306dfca047a0f4daa63e0c6c0d5ea632a8a40b855a

Contents?: true

Size: 1.59 KB

Versions: 9

Compression:

Stored size: 1.59 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, return_type: :path)
    end

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

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

      blob = source.try(:blob) || source
      proxy = Shimmer::FileProxy.new(blob_id: blob.id, width: width, height: height)
      case return_type
      when nil
        proxy
      when :path
        proxy.path
      when :url
        proxy.url
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
shimmer-0.0.39 lib/shimmer/utils/file_helper.rb
shimmer-0.0.38 lib/shimmer/utils/file_helper.rb
shimmer-0.0.37 lib/shimmer/utils/file_helper.rb
shimmer-0.0.36 lib/shimmer/utils/file_helper.rb
shimmer-0.0.35 lib/shimmer/utils/file_helper.rb
shimmer-0.0.34 lib/shimmer/utils/file_helper.rb
shimmer-0.0.33 lib/shimmer/utils/file_helper.rb
shimmer-0.0.32 lib/shimmer/utils/file_helper.rb
shimmer-0.0.31 lib/shimmer/utils/file_helper.rb