Skip to content

Instantly share code, notes, and snippets.

@flyerhzm
Forked from basgys/simple_paperclip.rb
Last active August 22, 2022 11:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flyerhzm/7289979 to your computer and use it in GitHub Desktop.
Save flyerhzm/7289979 to your computer and use it in GitHub Desktop.
paperclip without activerecord
class Image
extend ActiveModel::Naming
extend ActiveModel::Callbacks
include ActiveModel::Validations
include Paperclip::Glue
define_model_callbacks :save, only: [:after]
define_model_callbacks :destroy, only: [:before, :after]
attr_accessor :uuid, :attachment_file_name
has_attached_file :attachment,
styles: { three_dot_five_inch: "640x960>", four_inch: "640x1136>" },
path: ":rails_root/public/system/:attachment/:uuid_partition/:style/:filename",
url: "/system/:attachment/:uuid_partition/:style/:filename"
def to_model
self
end
def valid?() true end
def new_record?() true end
def destroyed?() true end
def errors
obj = Object.new
def obj.[](key) [] end
def obj.full_messages() [] end
def obj.any?() false end
obj
end
def initialize
@uuid = UUID.new.generate.gsub('-', '')
end
def save
run_callbacks :save do
end
end
def destroy
run_callbacks :destroy do
end
end
def as_json(options={})
{
uuid: uuid,
url: attachment.url(:four_inch)
}
end
end
class ImagesController < ApplicationController
before_action :authenticate_user!
def create
image = Image.new
image.attachment = params[:image]
image.save
render json: image
end
def show
image = Image.new
image.uuid = params[:id]
image.attachment_file_name = "image_message.png"
render json: {url: image.attachment.url(params[:style])}
end
end
Paperclip.interpolates :uuid_partition do |attachment, style|
attachment.instance.uuid.scan(/.{1,8}/m).join("/")
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment