Sha256: 668b4ed21f2a63907bb36572e6b2681fbefda06a9dee9c417493c831985c1dfb

Contents?: true

Size: 1.75 KB

Versions: 3

Compression:

Stored size: 1.75 KB

Contents

module Effective
  module Resources
    module Instance
      attr_reader :instance

      # This is written for use by effective_logging and effective_trash

      def instance
        @instance || klass.new
      end

      def instance_attributes
        return {} unless instance.present?

        attributes = { attributes: instance.attributes }

        # Collect to_s representations of all belongs_to associations
        belong_tos.each do |association|
          attributes[association.name] = instance.send(association.name).to_s
        end

        has_ones.each do |association|
          attributes[association.name] = instance.send(association.name).to_s
        end

        nested_resources.each do |association|
          attributes[association.name] = {}

          Array(instance.send(association.name)).each_with_index do |child, index|
            resource = Effective::Resource.new(child)
            attributes[association.name][index] = resource.instance_attributes
          end
        end

        attributes.delete_if { |_, value| value.blank? }
      end

      def instance_changes
        return {} unless (instance.present? && instance.changes.present?)

        changes = instance.changes.delete_if do |attribute, (before, after)|
          (before.kind_of?(ActiveSupport::TimeWithZone) && after.kind_of?(ActiveSupport::TimeWithZone) && before.to_i == after.to_i)
        end

        # Log to_s changes on all belongs_to associations
        belong_tos.each do |association|
          if (change = changes.delete(association.foreign_key)).present?
            changes[association.name] = [(association.klass.find_by_id(change.first) if changes.first), instance.send(association.name)]
          end
        end

        changes
      end

    end
  end
end




Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
effective_resources-0.3.10 app/models/effective/resources/instance.rb
effective_resources-0.3.9 app/models/effective/resources/instance.rb
effective_resources-0.3.8 app/models/effective/resources/instance.rb