Sha256: 3def0f39dad0967552006197a872a076a33f76ad8c4054582dca7f32fcbcfd06

Contents?: true

Size: 1.43 KB

Versions: 10

Compression:

Stored size: 1.43 KB

Contents

module Tenon
  module HasHistory
    class AttrSerializer
      def self.serialize(attrs, item_version)
        new(attrs, item_version).serialize
      end

      def initialize(attrs, item_version)
        @attrs = attrs || {}
        @item_version = item_version
        @item_class = item_version.item_type.constantize
        @item = @item_version.item
      end

      def serialize
        Marshal.dump(filtered_attrs)
      end

      private

      def filtered_attrs
        @attrs.to_h.deep_reject_key!(:id)
        @attrs.to_h.deep_reject_key!('id')
        require_only_attrs! unless only.empty?
        remove_except_attrs! unless except.empty?
        remove_children!
        @attrs
      end

      def require_only_attrs!
        @attrs = @attrs.select { |k, _| only.include?(k) }
      end

      def remove_except_attrs!
        @attrs = @attrs.reject { |k, _| except.include?(k.to_sym) }
      end

      def remove_children!
        @attrs = @attrs.reject do |k, _|
          key = k.to_s
          relation = key.gsub(/_attributes$/, '')
          key.match(/_attributes$/) && !includes.include?(relation)
        end
      end

      def only
        @item_class.instance_variable_get('@has_history_only')
      end

      def except
        @item_class.instance_variable_get('@has_history_except')
      end

      def includes
        @item_class.instance_variable_get('@has_history_includes').map(&:to_s)
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
tenon-2.1.0 lib/tenon/has_history/attr_serializer.rb
tenon-2.0.8 lib/tenon/has_history/attr_serializer.rb
tenon-2.0.7 lib/tenon/has_history/attr_serializer.rb
tenon-2.0.6 lib/tenon/has_history/attr_serializer.rb
tenon-2.0.5 lib/tenon/has_history/attr_serializer.rb
tenon-2.0.4 lib/tenon/has_history/attr_serializer.rb
tenon-2.0.3 lib/tenon/has_history/attr_serializer.rb
tenon-2.0.2 lib/tenon/has_history/attr_serializer.rb
tenon-2.0.1 lib/tenon/has_history/attr_serializer.rb
tenon-2.0.0 lib/tenon/has_history/attr_serializer.rb