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.
-
#derivatives_options ⇒ Object
Returns derivatives plugin options.
-
#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={}> }
572 573 574 575 576 577 578 579 580 581 582 583 584 |
# File 'lib/shrine/plugins/derivatives.rb', line 572 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_options ⇒ Object
Returns derivatives plugin options.
617 618 619 |
# File 'lib/shrine/plugins/derivatives.rb', line 617 def 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
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 |
# File 'lib/shrine/plugins/derivatives.rb', line 588 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 |