Class: ActiveShrine::Attachment

Inherits:
ActiveRecord::Base
  • Object
show all
Includes:
ActiveModel::Serializers::JSON
Defined in:
lib/active_shrine/attachment.rb

Instance Method Summary collapse

Instance Method Details

#content_typeObject



44
45
46
# File 'lib/active_shrine/attachment.rb', line 44

def content_type
  file.mime_type
end

#extensionObject



52
53
54
# File 'lib/active_shrine/attachment.rb', line 52

def extension
  file.extension
end

#file=(value) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/active_shrine/attachment.rb', line 66

def file=(value)
  # It is the same file. we are good to go.
  return if value == signed_id

  if value.is_a?(String)
    # it is an already uploaded file. either
    # - via direct upload so the form is sending us a json hash to set
    # - or was set because a previous submission failed, so the form is sending us the signed_id
    begin
      # attempt to parse as a json hash
      value = JSON.parse value
    rescue JSON::ParserError
      # this is not a valid json hash, let's check if it is a valid signed_id
      unsigned = Rails.application.message_verifier(:active_shrine_attachment).verify value
      value = JSON.parse unsigned["file"]
    end
  end

  super(value)
rescue ActiveSupport::MessageVerifier::InvalidSignature
  errors.add(:file, "is invalid")
end

#filenameObject



48
49
50
# File 'lib/active_shrine/attachment.rb', line 48

def filename
  file.original_filename
end

#purgeObject



89
90
91
92
# File 'lib/active_shrine/attachment.rb', line 89

def purge
  file_attacher.destroy_block { destroy } if file_attacher.respond_to?(:destroy_block)
  destroy
end

#purge_laterObject



94
95
96
97
98
99
100
101
# File 'lib/active_shrine/attachment.rb', line 94

def purge_later
  file_attacher.destroy_background
  file_attacher.instance_variable_set :@file, nil # prevent shrine from attempting to destroy the file again
  destroy
rescue NoMethodError
  raise NotImplementedError, ("You need to enable Shrine backgrounding to use purge_later: " \
                              "https://shrinerb.com/docs/plugins/backgrounding")
end

#representable?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/active_shrine/attachment.rb', line 56

def representable?
  %r{image/.*}.match? content_type
end

#signed_idObject



60
61
62
63
64
# File 'lib/active_shrine/attachment.rb', line 60

def signed_id
  # add the id to ensure uniqueness
  value = ({id:, file: file.to_json} if file.present?) || {}
  Rails.application.message_verifier(:active_shrine_attachment).generate value
end

#urlObject



40
41
42
# File 'lib/active_shrine/attachment.rb', line 40

def url
  file_url
end