Sha256: 1d9f8efbee0db237fc62650d2c362ea39b9653bae14034a8e9905f9c1fabad43

Contents?: true

Size: 1.67 KB

Versions: 8

Compression:

Stored size: 1.67 KB

Contents

module Effective
  class Trash < ActiveRecord::Base
    self.table_name = EffectiveTrash.trash_table_name.to_s

    belongs_to :trashed, polymorphic: true  # The original item type and id. Note that this object will never exist as it's deleted.
    belongs_to :user # The user that destroyed the original resource

    # Attributes
    # trashed_type       :string
    # trashed_id         :integer
    # trashed_to_s       :string
    # trashed_extra      :string

    # details            :text
    # timestamps

    serialize :details, Hash

    scope :deep, -> { includes(:user, :trashed) }
    scope :sorted, -> { order(:id) }

    def to_s
      trashed_to_s.presence || [trashed_type, trashed_id].join(' ').presence || 'New Trash item'
    end

    def details
      self[:details] || {}
    end

    def to_object
      raise 'no attributes to consider' unless details.kind_of?(Hash) && details[:attributes].present?

      resource = Effective::Resource.new(trashed_type)
      object = trashed_type.constantize.new(details[:attributes])

      resource.nested_resources.each do |association|
        if details[association.name].present? && object.respond_to?("#{association.name}_attributes=")
          nested_attributes = details[association.name].inject({}) do |h, (index, nested)|
            h[index] = nested[:attributes].except('id', association.inverse_of&.foreign_key); h
          end

          object.send("#{association.name}_attributes=", nested_attributes)
        end
      end

      object
    end

    # So this is a Trash item
    # When we delete ourselves, we restore this trash item first
    def restore!
      to_object.save!(validate: false)
      destroy!
    end

  end
end


Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
effective_trash-0.4.3 app/models/effective/trash.rb
effective_trash-0.4.2 app/models/effective/trash.rb
effective_trash-0.4.1 app/models/effective/trash.rb
effective_trash-0.4.0 app/models/effective/trash.rb
effective_trash-0.3.3 app/models/effective/trash.rb
effective_trash-0.3.2 app/models/effective/trash.rb
effective_trash-0.3.1 app/models/effective/trash.rb
effective_trash-0.3.0 app/models/effective/trash.rb