module Shrine::Plugins::Derivatives::ClassMethods

  1. lib/shrine/plugins/derivatives.rb

Public Instance methods

derivatives(object)

Converts data into a Hash of derivatives.

Shrine.derivatives('{"thumb":{"id":"foo","storage":"store","metadata":{}}}')
#=> { thumb: #<Shrine::UploadedFile id="foo" storage=:store metadata={}> }

Shrine.derivatives({ "thumb" => { "id" => "foo", "storage" => "store", "metadata" => {} } })
#=> { thumb: #<Shrine::UploadedFile id="foo" storage=:store metadata={}> }

Shrine.derivatives({ thumb: { id: "foo", storage: "store", metadata: {} } })
#=> { thumb: #<Shrine::UploadedFile id="foo" storage=:store metadata={}> }
[show source]
    # File lib/shrine/plugins/derivatives.rb
568 def derivatives(object)
569   if object.is_a?(String)
570     derivatives JSON.parse(object)
571   elsif object.is_a?(Hash) || object.is_a?(Array)
572     map_derivative(
573       object,
574       transform_keys: :to_sym,
575       leaf: -> (value) { value.is_a?(Hash) && (value["id"] || value[:id]).is_a?(String) },
576     ) { |_, value| uploaded_file(value) }
577   else
578     fail ArgumentError, "cannot convert #{object.inspect} to derivatives"
579   end
580 end
derivatives_options()

Returns derivatives plugin options.

[show source]
    # File lib/shrine/plugins/derivatives.rb
613 def derivatives_options
614   opts[:derivatives]
615 end
map_derivative(object, path = [], transform_keys: :to_sym, leaf: nil, &block)

Iterates over a nested collection, yielding on each part of the path. If the block returns a truthy value, that branch is terminated

[show source]
    # File lib/shrine/plugins/derivatives.rb
584 def map_derivative(object, path = [], transform_keys: :to_sym, leaf: nil, &block)
585   return enum_for(__method__, object) unless block_given?
586 
587   if leaf && leaf.call(object)
588     yield path, object
589   elsif object.is_a?(Hash)
590     object.inject({}) do |hash, (key, value)|
591       key = key.send(transform_keys)
592 
593       hash.merge! key => map_derivative(
594         value, [*path, key],
595         transform_keys: transform_keys, leaf: leaf,
596         &block
597       )
598     end
599   elsif object.is_a?(Array)
600     object.map.with_index do |value, idx|
601       map_derivative(
602         value, [*path, idx],
603         transform_keys: transform_keys, leaf: leaf,
604         &block
605       )
606     end
607   else
608     yield path, object
609   end
610 end