Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Subclass for chained URLs (Imgproxy Pro) #219

Open
edtjones opened this issue Apr 19, 2023 · 0 comments
Open

Subclass for chained URLs (Imgproxy Pro) #219

edtjones opened this issue Apr 19, 2023 · 0 comments

Comments

@edtjones
Copy link

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant