Module: DecoratorDryer::ActiveStorageShortcuts::ClassMethods

Defined in:
lib/decorator_dryer/active_storage_shortcuts.rb

Instance Method Summary collapse

Instance Method Details

#to_attachment(*attrs, preview_transform: nil) ⇒ Object



11
12
13
14
15
16
# File 'lib/decorator_dryer/active_storage_shortcuts.rb', line 11

def to_attachment(*attrs, preview_transform: nil)
  to_attachment_url(*attrs)
  to_attachment_name(*attrs)
  to_attachment_preview(*attrs, transform: preview_transform)
  to_attachment_signed_id(*attrs)
end

#to_attachment_name(*attrs) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/decorator_dryer/active_storage_shortcuts.rb', line 30

def to_attachment_name(*attrs)
  attrs.each do |attr|
    method_name = "#{attr}_name".to_sym

    define_method(method_name) do
      attachment = object.send(attr)

      attachment.blob.filename.as_json if attachment.attached?
    end
  end
end

#to_attachment_preview(*attrs, transform: nil) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/decorator_dryer/active_storage_shortcuts.rb', line 42

def to_attachment_preview(*attrs, transform: nil)
  transform ||= DecoratorDryer.configuration.attachment_shortcuts.default_preview_transform

  attrs.each do |attr|
    method_name = "#{attr}_preview".to_sym

    define_method(method_name) do
      return if transform.blank? || transform == :none

      attachment = object.send(attr)
      return unless attachment.attached?

      if transform.is_a? Symbol
        url_for attachment.variant(transform)
      else
        return unless attachment.representable?

        url_for attachment.representation(transform).processed
      end
    end
  end
end

#to_attachment_signed_id(*attrs) ⇒ Object



65
66
67
68
69
70
71
72
73
74
# File 'lib/decorator_dryer/active_storage_shortcuts.rb', line 65

def to_attachment_signed_id(*attrs)
  attrs.each do |attr|
    method_name = "#{attr}_signed_id".to_sym

    define_method(method_name) do
      attachment = object.send(attr)
      attachment.signed_id if attachment.attached?
    end
  end
end

#to_attachment_url(*attrs) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
# File 'lib/decorator_dryer/active_storage_shortcuts.rb', line 18

def to_attachment_url(*attrs)
  attrs.each do |attr|
    method_name = "#{attr}_url".to_sym

    define_method(method_name) do
      attachment = object.send(attr)

      url_for(attachment) if attachment.attached?
    end
  end
end