Sha256: be47b46ecd7b4e0b79f5e72589286f02c3ef938bc262236be3a46719b7f9b180

Contents?: true

Size: 1.09 KB

Versions: 5

Compression:

Stored size: 1.09 KB

Contents

module Attachs
  module Concern
    extend ActiveSupport::Concern

    included do
      before_save :persist_attachments
      after_commit :save_attachments, on: %i(create update)
      after_commit :destroy_attachments, on: :destroy
      after_rollback :unpersist_attachments
    end

    def reload(options=nil)
      clear_attachments
      super
    end

    private

    def initialize_dup(other)
      clear_attachments
      super
    end

    def clear_attachments
      self.class.attachments.keys.each do |attribute|
        instance_variable_set "@#{attribute}", nil
      end
    end

    %i(save destroy persist unpersist).each do |method|
      define_method "#{method}_attachments" do
        self.class.attachments.keys.each do |attribute|
          send(attribute).send method
        end
      end
    end

    module ClassMethods

      def inherited(subclass)
        subclass.instance_variable_set :@attachments, @attachments
        super
      end

      def attachments
        @attachments ||= {}
      end

      def attachable?
        attachments.any?
      end

    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
attachs-4.0.0.5 lib/attachs/concern.rb
attachs-4.0.0.4 lib/attachs/concern.rb
attachs-4.0.0.3 lib/attachs/concern.rb
attachs-4.0.0.2 lib/attachs/concern.rb
attachs-4.0.0.1 lib/attachs/concern.rb