Paste
Pasted as Ruby by foht ( 6 years ago )
require "google/cloud/storage"
class Project < ApplicationRecord
def self.storage_bucket
@storage_bucket ||= begin
config = Rails.configuration.gcs
storage = Google::Cloud::Storage.new project_id: config['project_id'],
credentials: config['keyfile']
storage.bucket config['bucket']
end
end
# validates :name, presence: true
# validates :description, presence: true
attr_accessor :image
private
after_create :upload_images
before_update :upload_images, if: :image
def upload_images
upload_image("lg", "612x612")
upload_image("md", "408x408")
upload_image("sm", "340x340")
upload_hero("lg", 1920, 700)
upload_hero("mdlg", 1350, 700)
upload_hero("md", 1200, 700)
upload_hero("sm", 768, 700)
end
# def delete_image
# image_uri = URI.parse image_lg_url
# if image_uri.host == "#{Project.storage_bucket.name}.storage.googleapis.com"
# image_path = image_uri.path.sub("/", "")
# file = Project.storage_bucket.file image_path
# file.delete
# end
# end
def upload_hero(type, width, height)
hero = MiniMagick::Image.new(image.path)
hero.combine_options do |i|
i.gravity(:center)
i.crop "#{width}x#{height}+0+0!"
end
file = Project.storage_bucket.create_file \
hero.path,
"images/#{id}/hero/#{type}_#{image.original_filename}",
content_type: image.content_type,
acl: "public"
update_columns "hero_#{type}_url": file.public_url
end
def upload_image(type, size)
img = MiniMagick::Image.new(image.path)
img.resize(size)
file = Project.storage_bucket.create_file \
img.path,
"images/#{id}/thumbnail/#{type}_#{image.original_filename}",
content_type: image.content_type,
acl: "public"
update_columns "image_#{type}_url": file.public_url
end
end
Revise this Paste