Created
February 18, 2016 12:22
-
-
Save sebyx07/0bd2db411290de639df0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class AdImageHandler | |
attr_reader :model, :data, :file_path, :file_name | |
def initialize(model, data, image_index) | |
@model = model | |
@data = data | |
@file_name = SecureRandom.uuid | |
@file_path = AdImageHandler.generate_image_path(@file_name) | |
@image_index = image_index | |
end | |
def write_initial_file | |
uri = URI::Data.new(@data) | |
File.open @file_path, 'wb' do |file| | |
file.write(uri.data) | |
end | |
end | |
def resize_image_file | |
MiniMagick::Tool::Mogrify.new do |m| | |
m.format 'png' | |
m << @file_path | |
end | |
end | |
def clean_old_file | |
old_file_name = @model.base_images[@image_index] | |
old_file_path = AdImageHandler.generate_image_path(old_file_name) | |
if File.exist?(old_file_path) | |
File.delete(old_file_path) | |
end | |
end | |
def save_image_to_model | |
@model.base_images[@image_index] = @file_name | |
end | |
def save | |
write_initial_file | |
resize_image_file | |
clean_old_file | |
save_image_to_model | |
end | |
class << self | |
def generate_image_path(name) | |
"#{ENV['HOME']}/images/#{name}.png" | |
end | |
end | |
end | |
class Controller | |
def upload_images | |
data = params["image_#{index}"] | |
if data | |
img_handler = AdImageHandler.new(@ad, data, index) | |
img_handler.save | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment