Sha256: f72ac76914b5ae9858141b8a0ce07835991f7e0f2f04db63bcb93359d1b7f799

Contents?: true

Size: 1.32 KB

Versions: 3

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

module Paperweight
  # Overrides the `has_attached_file` method from `paperclip` so that
  # `paperweight` can add extras when the macro is called.
  module Hook
    # Converts a parent name to its respective component child names.
    class AttachmentName
      attr_reader :name

      def initialize(name)
        @name = name
      end

      def processing
        :"#{name}_processing"
      end

      def url
        :"#{name}_url"
      end

      def url_eq
        :"#{name}_url="
      end

      def url_attr
        :"@#{name}_url"
      end
    end

    def has_attached_file(name, *) # rubocop:disable Naming/PredicateName
      super

      name = AttachmentName.new(name)
      attr_reader name.url

      define_paperweight_setter_for(name)
      define_paperweight_after_commit_for(name)
    end

    private

    def define_paperweight_setter_for(name)
      define_method(name.url_eq) do |value|
        instance_variable_set(name.url_attr, value)
        self[name.processing] = value ? true : false
        self.updated_at = Time.now if value
      end
    end

    def define_paperweight_after_commit_for(name)
      after_commit if: name.url do
        attachment_url = public_send(name.url)
        PostProcessJob.perform_later(self, name.name.to_s, attachment_url)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
paperweight-0.2.0 lib/paperweight/hook.rb
paperweight-0.1.2 lib/paperweight/hook.rb
paperweight-0.1.1 lib/paperweight/hook.rb