Skip to content

Subclass for chained URLs (Imgproxy Pro) #219

@edtjones

Description

@edtjones

Hi folks,

I needed to create chained URLs, so I came up with a simple subclass of Imgproxy::Builder which I thought might be useful to others. I just stuck it in a Rails initializer.

Instead of Imgproxy::Builder.new({your: :options}) you pass an array of options as the first argument, and any builder options as the second argument:

Imgproxy::ChainedBuilder.new([{width: 512}, {crop: {height: 340, gravity: :obj}}]).url_for('your-image-url-here')

It's a bit rough, and not worthy of a PR, but I thought it might be useful to others.

module Imgproxy
  class ChainedBuilder < Imgproxy::Builder

    def initialize(option_groups = [], options = {})
      option_groups = option_groups.dup

      @option_groups = option_groups.map do |options|
        Imgproxy::Options.new(options)
      end
      extract_builder_options(options)
      @format = options.delete(:format)

    end

    # build a chained builder. Grouped processing options are an array of the groups of processing options, thus:
    # [
    #   ["width: 1024"],
    #   ["crop:h:300"]
    # ]
    # They need to be on the url separated by a /-/
    def url_for(image)
      path_parts = grouped_processing_options.inject([]) do |a, opts|
        a.push(opts)
        a.push("-")
        a
      end
      path = path_parts.push(url(image, ext: @format)).join("/")
      signature = sign_path(path)
      File.join(Imgproxy.config.endpoint.to_s, signature, path)
    end

    # Build an array of processing options, which will need to be separated by a /-/ in the url
    def grouped_processing_options
      @grouped_processing_options ||= @option_groups.map do |group|
        group.map do |key, value|
          [option_alias(key), value].join(":")
        end
      end
    end
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions