Created
April 9, 2020 03:01
-
-
Save jordanhudgens/c80e0886adbb2d955d10c3478935c64c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Create a helper lib | |
# e.g. lib/image_encoder.rb | |
module ImageEncoder | |
def self.call(image_data, resource_name, model) | |
image_data.match(/(image\/[a-z]{3,4});base64,(.*)/) do |match| | |
content_type = match[1] | |
decoded_data = Base64.decode64(match[2]) | |
temp = Tempfile.open("image", encoding: "ascii-8bit") | |
temp.write(decoded_data) | |
temp.rewind | |
model.send(resource_name).attach(content_type: content_type, io: temp, filename: "img.png") | |
end | |
end | |
end | |
# Then call from a model file, such as: app/models/organization.rb | |
class Organization < ApplicationRecord | |
include ImageEncoder | |
has_one_attached :logo | |
def logo_raw=(logo_image_data) | |
ImageEncoder.call(logo_image_data, "logo", self) | |
end | |
def logo_url | |
if self.logo.attachment | |
self.logo.attachment.service_url | |
else | |
"https://some-default-path-to-image.png" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment