Module: Shrine::Plugins::Derivatives::ClassMethods

Defined in:
lib/shrine/plugins/derivatives.rb

Instance Method Summary collapse

Instance Method Details

#derivatives(object) ⇒ 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={}> }

560
561
562
563
564
565
566
567
568
569
570
571
572
# File 'lib/shrine/plugins/derivatives.rb', line 560

def derivatives(object)
  if object.is_a?(String)
    derivatives JSON.parse(object)
  elsif object.is_a?(Hash) || object.is_a?(Array)
    map_derivative(
      object,
      transform_keys: :to_sym,
      leaf: -> (value) { value.is_a?(Hash) && (value["id"] || value[:id]).is_a?(String) },
    ) { |_, value| uploaded_file(value) }
  else
    fail ArgumentError, "cannot convert #{object.inspect} to derivatives"
  end
end

#derivatives_optionsObject

Returns derivatives plugin options.


605
606
607
# File 'lib/shrine/plugins/derivatives.rb', line 605

def derivatives_options
  opts[:derivatives]
end

#map_derivative(object, path = [], transform_keys: :to_sym, leaf: nil, &block) ⇒ Object

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


576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# File 'lib/shrine/plugins/derivatives.rb', line 576

def map_derivative(object, path = [], transform_keys: :to_sym, leaf: nil, &block)
  return enum_for(__method__, object) unless block_given?

  if leaf && leaf.call(object)
    yield path, object
  elsif object.is_a?(Hash)
    object.inject({}) do |hash, (key, value)|
      key = key.send(transform_keys)

      hash.merge! key => map_derivative(
        value, [*path, key],
        transform_keys: transform_keys, leaf: leaf,
        &block
      )
    end
  elsif object.is_a?(Array)
    object.map.with_index do |value, idx|
      map_derivative(
        value, [*path, idx],
        transform_keys: transform_keys, leaf: leaf,
        &block
      )
    end
  else
    yield path, object
  end
end