Sha256: 37af793bf310d1a14d2ae47a8d5b23efe62b63f3c42c7d45a4a0572b9d1b59a3

Contents?: true

Size: 1.97 KB

Versions: 23

Compression:

Stored size: 1.97 KB

Contents

module ::Logical::Naf
  class Pickler
    include ::Af::Application::Component

    create_proxy_logger
    attr_reader :preserves,
                :preservables,
                :naf_version,
                :context

    def initialize(naf_version, preservables)
      @preservables = preservables
      @naf_version = naf_version
      @preserves = {}
      @context = {}
    end

    def generic_pickle(instance, associations = nil, ignored_attributes = [:created_at, :updated_at])
      instance_attributes = instance.attributes.symbolize_keys
      ignored_attributes.each do |ignored_attribute|
        instance_attributes.delete(ignored_attribute.to_sym)
      end

      unless associations
        associations = {}
        instance_attributes.keys.select{|key| key.to_s =~ /_id$/}.each do |key|
          association_name = key.to_s[0..-4].to_sym
          association = instance.association(association_name) rescue nil
          if association
            associations[key] = association.options[:class_name].constantize.name
          end
        end
      end

      return Hash[instance_attributes.map { |key,value|
                    if associations[key]
                      [key, { association_model_name: associations[key], association_value: value }]
                    else
                      [key,value]
                    end
                  } ]
    end

    def preserve
      @preservables.each do |model|
        preserve_model(model)
      end
    end

    def preserve_model(model)
      if model.respond_to?(:pickleables)
        pickables = model.pickleables(self)
      else
        pickables = model.all
      end

      @preserves[model.name] = pickables.map do |instance|
        if instance.respond_to?(:pickle)
          instance.pickle(self)
        else
          generic_pickle(instance)
        end
      end
    end

    def pickle_jar
      {
        version: @naf_version,
        preserved_at: Time.now,
        preserves: @preserves
      }
    end
  end
end

Version data entries

23 entries across 23 versions & 1 rubygems

Version Path
naf-1.1.2 app/models/logical/naf/pickler.rb
naf-1.1.1 app/models/logical/naf/pickler.rb
naf-1.1.0 app/models/logical/naf/pickler.rb