aboutsummaryrefslogtreecommitdiffstats
path: root/lib/active_storage/variation.rb
blob: f7c81bb99a36719087b630398e7e4559ecba0231 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
require "active_support/core_ext/object/inclusion"

# A set of transformations that can be applied to a blob to create a variant.
class ActiveStorage::Variation
  class_attribute :verifier

  attr_reader :transformations

  class << self
    def decode(key)
      new verifier.verify(key)
    end

    def encode(transformations)
      verifier.generate(transformations)
    end
  end

  def initialize(transformations)
    @transformations = transformations
  end

  def transform(image)
    transformations.each do |(method, argument)|
      if eligible_argument?(argument)
        image.public_send(method, argument)
      else
        image.public_send(method)
      end
    end
  end

  def key
    self.class.encode(transformations)
  end

  private
    def eligible_argument?(argument)
      argument.present? && argument != true
    end
end