Sha256: 13585501e2360297dd560b1fa800d453b8da9dc0ff14a2d8863a5a8c87f787d6

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

module JsonReducer
  class Mask
    def initialize(schema)
      @schema = parse_record(schema)
    end

    def apply(payload)
      payload = parse_record(payload).dup
      apply!(payload, @schema)

      payload
    end

    private

    def apply!(payload, schema)
      return if schema.dig('properties').nil?

      # sliced = payload.slice!(*schema['properties'].keys)
      sliced = slice!(payload, schema['properties'].keys)
      handle(schema['properties'], sliced)
    end

    def handle(properties, payload)
      properties.each do |key, property|
        case property['type']
        when 'array'
          payload[key].each { |hash| apply!(hash, property) }
        when 'object'
          apply!(payload[key], property)
        end
      end
    end

    def parse_record(schema)
      schema.is_a?(String) ? JSON.parse(schema) : schema
    end

    def slice!(hash, keys)
      sliced = hash.slice(*keys)
      sliced.default      = hash.default
      sliced.default_proc = hash.default_proc if hash.default_proc
      hash.replace(sliced)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
json_reducer-0.1.0 lib/json_reducer/mask.rb