Skip to content

Instantly share code, notes, and snippets.

@jordanhudgens
Created April 9, 2020 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jordanhudgens/c80e0886adbb2d955d10c3478935c64c to your computer and use it in GitHub Desktop.
Save jordanhudgens/c80e0886adbb2d955d10c3478935c64c to your computer and use it in GitHub Desktop.
# 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