Sha256: 8b58d6681a0a0f38028fb2cee776da04efbb9702368ad3545f96ff7705d618bf

Contents?: true

Size: 1017 Bytes

Versions: 16

Compression:

Stored size: 1017 Bytes

Contents

module Almanack
  class SerializedTransformation

    def initialize(subject)
      @subject = subject
      @transformations = {}
    end

    def key(&block)
      @transformations[:key] = block
    end

    def value(&block)
      @transformations[:value] = block
    end

    def apply
      recurse(cloned)
    end

    private

    def cloned
      @subject.dup
    end

    def recursable?(node)
      node.is_a?(Array) || node.is_a?(Hash)
    end

    def no_change
      -> (obj) { obj }
    end

    def transformation(type, entity)
      (@transformations[type] || no_change).call(entity)
    end

    def recurse(entity)
      case entity
      when Array
        entity.map { |child| recurse(child) }
      when Hash
        entity.each_with_object({}) do |(key, value), hash|
          transformed_key = recursable?(key) ? recurse(key) : transformation(:key, key)
          hash[transformed_key] = recurse(value)
        end
      else
        transformation(:value, entity)
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
almanack-1.3.1 lib/almanack/serialized_transformation.rb
almanack-1.3.0 lib/almanack/serialized_transformation.rb
almanack-1.3.0.rc1 lib/almanack/serialized_transformation.rb
almanack-1.2.1 lib/almanack/serialized_transformation.rb
almanack-1.2.0 lib/almanack/serialized_transformation.rb
almanack-1.1.5 lib/almanack/serialized_transformation.rb
almanack-1.1.3 lib/almanack/serialized_transformation.rb
almanack-1.1.3.rc1 lib/almanack/serialized_transformation.rb
almanack-1.1.2 lib/almanack/serialized_transformation.rb
almanack-1.1.1 lib/almanack/serialized_transformation.rb
almanack-1.1.0 lib/almanack/serialized_transformation.rb
almanack-1.1.0.beta6 lib/almanack/serialized_transformation.rb
almanack-1.1.0.beta5 lib/almanack/serialized_transformation.rb
almanack-1.1.0.beta4 lib/almanack/serialized_transformation.rb
almanack-1.1.0.beta3 lib/almanack/serialized_transformation.rb
almanack-1.1.0.beta2 lib/almanack/serialized_transformation.rb