diff options
author | David Heinemeier Hansson <david@loudthinking.com> | 2017-07-21 15:51:31 -0500 |
---|---|---|
committer | David Heinemeier Hansson <david@loudthinking.com> | 2017-07-21 15:51:31 -0500 |
commit | 7f4111185ca6286adbe0ffc1346d416c5fa7dfd3 (patch) | |
tree | e3de354e39b5913e532910c2cfc1f90686dcf6bb /lib/active_storage/variation.rb | |
parent | 0c47740d858cb04c7165bce411584c3b05d155b6 (diff) | |
download | rails-7f4111185ca6286adbe0ffc1346d416c5fa7dfd3.tar.gz rails-7f4111185ca6286adbe0ffc1346d416c5fa7dfd3.tar.bz2 rails-7f4111185ca6286adbe0ffc1346d416c5fa7dfd3.zip |
Extract variation value object
Diffstat (limited to 'lib/active_storage/variation.rb')
-rw-r--r-- | lib/active_storage/variation.rb | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/lib/active_storage/variation.rb b/lib/active_storage/variation.rb new file mode 100644 index 0000000000..abff288ac1 --- /dev/null +++ b/lib/active_storage/variation.rb @@ -0,0 +1,53 @@ +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 + + ALLOWED_TRANSFORMATIONS = %i( + resize rotate format flip fill monochrome orient quality roll scale sharpen shave shear size thumbnail + transparent transpose transverse trim background bordercolor compress crop + ) + + 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)| + next unless eligible_transformation?(method) + + 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_transformation?(method) + method.to_sym.in?(ALLOWED_TRANSFORMATIONS) + end + + # FIXME: Consider whitelisting allowed arguments as well? + def eligible_argument?(argument) + argument.present? && argument != true + end +end |