Advertisement
NameL3ss

valid base64 rails

Jul 21st, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. # frozen_string_literal: true
  2.  
  3. module Imageable
  4. extend ActiveSupport::Concern
  5.  
  6. included do
  7. before_save :upload_image
  8. end
  9.  
  10. def img_attribute
  11. self.class.reflect_on_all_attachments
  12. .filter{ |association| association.instance_of? ActiveStorage::Reflection::HasOneAttachedReflection }
  13. .map(&:name).join.to_sym
  14. end
  15.  
  16. def img_attribute_size
  17. self.class::SIZE_IMG
  18. end
  19.  
  20. def img_attribute_content
  21. send("#{img_attribute}_content")
  22. end
  23.  
  24. def klass_name
  25. self.class.model_name.singular
  26. end
  27.  
  28. def valid_image_format
  29. acceptable_types = %w[image/jpeg image/png]
  30. unless acceptable_types.include?(content_type_upload)
  31. errors.add(img_attribute, I18n.t('record.errors.wrong_content_type_img'))
  32. return false
  33. end
  34. true
  35. end
  36.  
  37. def valid_image_size
  38. if send(img_attribute).blob.byte_size > img_attribute_size
  39. errors.add(img_attribute, I18n.t('record.errors.wrong_size_img', size_img: img_attribute))
  40. return false
  41. end
  42. true
  43. end
  44.  
  45. def check_if_file_exist
  46. unless decode64_img
  47. errors.add(img_attribute, I18n.t('record.errors.file_not_exist'))
  48. raise ActiveRecord::Rollback
  49. end
  50. true
  51. end
  52.  
  53. def acceptable_image
  54. return unless send(img_attribute).attached?
  55.  
  56. if valid_image_format && valid_image_size
  57. true
  58. else
  59. send(img_attribute).purge
  60. raise ActiveRecord::Rollback
  61. end
  62. end
  63.  
  64. def upload_image
  65. return unless img_attribute_content.present? && content_type.present? && check_if_file_exist
  66.  
  67. blob = ActiveStorage::Blob.create_after_upload!(
  68. io: decode64_img,
  69. content_type: content_type,
  70. filename: "#{klass_name}-#{SecureRandom.hex(7)}.#{file_extension}"
  71. )
  72. new_record? ? send(img_attribute).attach(blob) : send("#{img_attribute}=", blob)
  73. acceptable_image
  74. end
  75.  
  76. def extract_base64
  77. img_attribute_content.sub(/^data:.*,/, '')
  78. end
  79.  
  80. def decode64_img
  81. file = Base64.decode64(extract_base64)
  82. File.open(file) if File.exist?(file)
  83. end
  84.  
  85. def file_extension
  86. content_type.try(:split, '/')[1]
  87. end
  88.  
  89. def content_type_upload
  90. Rack::Mime.mime_type(File.extname(decode64_img))
  91. end
  92. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement