Sha256: 40613a413dbce948aaa0e14c6e43ac44f533c381d2095bfabc5f56b15be174fd

Contents?: true

Size: 1.39 KB

Versions: 11

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

module TableSync::Publishing::Helpers
  class Attributes
    BASE_SAFE_JSON_TYPES = [
      NilClass,
      String,
      TrueClass,
      FalseClass,
      Numeric,
      Symbol,
    ].freeze

    # add custom seializables?

    NOT_MAPPED = Object.new

    attr_reader :attributes

    def initialize(attributes)
      @attributes = attributes.deep_symbolize_keys
    end

    def serialize
      filter_safe_for_serialization(attributes)
    end

    def filter_safe_for_serialization(object)
      case object
      when Array
        object.each_with_object([]) do |value, memo|
          value = filter_safe_for_serialization(value)
          memo << value if object_mapped?(value)
        end
      when Hash
        object.each_with_object({}) do |(key, value), memo|
          key = filter_safe_for_serialization(key)
          value = filter_safe_hash_values(value)
          memo[key] = value if object_mapped?(key) && object_mapped?(value)
        end
      when Float::INFINITY
        NOT_MAPPED
      when *BASE_SAFE_JSON_TYPES
        object
      else # rubocop:disable Lint/DuplicateBranch
        NOT_MAPPED
      end
    end

    def filter_safe_hash_values(value)
      case value
      when Symbol
        value.to_s # why?
      else
        filter_safe_for_serialization(value)
      end
    end

    def object_mapped?(object)
      object != NOT_MAPPED
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
table_sync-6.5.1 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.5.0 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.4.2 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.4.1 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.4.0 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.3.0 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.1.0 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.0.4 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.0.3 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.0.2 lib/table_sync/publishing/helpers/attributes.rb
table_sync-6.0 lib/table_sync/publishing/helpers/attributes.rb