Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # frozen_string_literal: true
- module Imageable
- extend ActiveSupport::Concern
- included do
- before_save :upload_image
- end
- def img_attribute
- self.class.reflect_on_all_attachments
- .filter{ |association| association.instance_of? ActiveStorage::Reflection::HasOneAttachedReflection }
- .map(&:name).join.to_sym
- end
- def img_attribute_size
- self.class::SIZE_IMG
- end
- def img_attribute_content
- send("#{img_attribute}_content")
- end
- def klass_name
- self.class.model_name.singular
- end
- def valid_image_format
- acceptable_types = %w[image/jpeg image/png]
- unless acceptable_types.include?(content_type_upload)
- errors.add(img_attribute, I18n.t('record.errors.wrong_content_type_img'))
- return false
- end
- true
- end
- def valid_image_size
- if send(img_attribute).blob.byte_size > img_attribute_size
- errors.add(img_attribute, I18n.t('record.errors.wrong_size_img', size_img: img_attribute))
- return false
- end
- true
- end
- def check_if_file_exist
- unless decode64_img
- errors.add(img_attribute, I18n.t('record.errors.file_not_exist'))
- raise ActiveRecord::Rollback
- end
- true
- end
- def acceptable_image
- return unless send(img_attribute).attached?
- if valid_image_format && valid_image_size
- true
- else
- send(img_attribute).purge
- raise ActiveRecord::Rollback
- end
- end
- def upload_image
- return unless img_attribute_content.present? && content_type.present? && check_if_file_exist
- blob = ActiveStorage::Blob.create_after_upload!(
- io: decode64_img,
- content_type: content_type,
- filename: "#{klass_name}-#{SecureRandom.hex(7)}.#{file_extension}"
- )
- new_record? ? send(img_attribute).attach(blob) : send("#{img_attribute}=", blob)
- acceptable_image
- end
- def extract_base64
- img_attribute_content.sub(/^data:.*,/, '')
- end
- def decode64_img
- file = Base64.decode64(extract_base64)
- File.open(file) if File.exist?(file)
- end
- def file_extension
- content_type.try(:split, '/')[1]
- end
- def content_type_upload
- Rack::Mime.mime_type(File.extname(decode64_img))
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement