class Shrink::Wrap::Transformer::CollectionFromKey

Public Class Methods

new(opts = {}) click to toggle source
Calls superclass method Shrink::Wrap::Transformer::Base::new
# File lib/shrink/wrap/transformer/collection_from_key.rb, line 9
def initialize(opts = {})
  unless valid_options?(opts)
    raise ArgumentError, 'options must contain one key/value pair'
  end

  super
end

Public Instance Methods

transform(input) click to toggle source
# File lib/shrink/wrap/transformer/collection_from_key.rb, line 17
def transform(input)
  ensure_type!(Hash, input)
  from, to = options.first
  data = input[from]
  return input unless data.is_a?(Hash)

  mapped = map(data, to)
  input.merge(from => mapped)
end

Private Instance Methods

map(data, to) click to toggle source
# File lib/shrink/wrap/transformer/collection_from_key.rb, line 29
def map(data, to)
  data.map do |key, value|
    if value.is_a?(Hash)
      value.merge(to => key)
    else
      { to => key, value: value }
    end
  end
end
valid_options?(opts) click to toggle source
# File lib/shrink/wrap/transformer/collection_from_key.rb, line 39
def valid_options?(opts)
  opts.is_a?(Hash) && opts.size == 1
end