Module: Shrine::Plugins::Derivatives::ClassMethods
- Defined in:
- lib/shrine/plugins/derivatives.rb
Instance Method Summary collapse
-
#derivatives(object) ⇒ Object
Converts data into a Hash of derivatives.
-
#map_derivative(object, path = [], transform_keys: :to_sym, leaf: nil, &block) ⇒ Object
Iterates over a nested collection, yielding on each part of the path.
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={}> }
537 538 539 540 541 542 543 544 545 546 547 548 549 |
# File 'lib/shrine/plugins/derivatives.rb', line 537 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 |
#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
553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 |
# File 'lib/shrine/plugins/derivatives.rb', line 553 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 |