# config/initializers/shrine.rb
require 'shrine'
require 'shrine/storage/file_system'
Shrine.storages = {
cache: Shrine::Storage::FileSystem.new('public', prefix: 'uploads/cache'), # temporary
store: Shrine::Storage::FileSystem.new('public', prefix: 'uploads/store'), # permanent
}# app/models/creative.rb
class Creative < ActiveRecord::Base
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to :kind, class_name: 'CreativeKind', foreign_key: :creative_kind_id
has_many :attachments, inverse_of: :creative, dependent: :destroy
accepts_nested_attributes_for :attachments, allow_destroy: true, reject_if: :all_blank
end# app/models/creative_kind.rb
class CreativeKind < ActiveHash::Base include ActiveHash::Associations include ActiveHash::Enum
belongs_to :creatives
self.data = [ { id: 1, name: 'Image' }, { id: 2, name: 'HTML' }, { id: 3, name: 'Dynamic' } ]
enum_accessor :nameend# app/models/attachment.rb
class Attachment < ActiveRecord::Base
include FileUploader[:file]
belongs_to :creative, inverse_of: :attachments
end# app/uploaders/file_uploader.rb
require 'image_processing/mini_magick'
class FileUploader < Shrine
include ImageProcessing::MiniMagick
plugin :activerecord
plugin :logging, logger: Rails.logger
plugin :validation_helpers
plugin :determine_mime_type
plugin :processing
plugin :versions
plugin :store_dimensions
plugin :cached_attachment_data
plugin :restore_cached_data
plugin :pretty_location
plugin :remove_attachment
plugin :remove_invalid
plugin :delete_promoted
THUMB_VERSION_LONGEST_SIDE = 150
Attacher.validate do
validate_max_size 10.megabytes, message: 'is too large (max is 10 MB)'
# kind = CreativeKind.find(kind_id).name # I don't know how to get the value of the kind id
# # case kind # when 'Image' # validate_mime_type_inclusion ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'] # when 'HTML' # validate_mime_type_inclusion ['image/jpg', 'image/jpeg', 'image/png', 'image/gif', 'text/html'] # when 'Dynamic' # validate_mime_type_inclusion [] # Unknown at this moment # end end
process(:store) do |io, context|
{ original: io, thumb: thumb_version(io) }
end
private
def thumb_version(io)
resize_to_limit!(io.download, THUMB_VERSION_LONGEST_SIDE, THUMB_VERSION_LONGEST_SIDE)
end
end# app/controllers/creatives_controller.rb
class CreativesController < ApplicationController
def new
@creative = Creative.new
@creative.attachments.build
end
def create
@creative = Creative.new(creative_params)
if @creative.save
redirect_to creative_url(@creative), notice: 'Creative was successfully created.'
else
@creative.attachments.build if @creative.attachments.empty?
render :new
end
end
def edit
@creative = Creative.find(params[:id])
@creative.attachments.build
end
def update
@creative = Creative.find(params[:id])
if @creative.update(creative_params)
redirect_to creative_url(@creative), notice: 'Creative was successfully updated.'
else
@creative.attachments.build if @creative.attachments.all?(&:persisted?)
render :edit
end
end
private
def creative_params
params.require(:creative).permit(:creative_kind_id, attachments_attributes: [:file, :id, :_destroy])
end
end# app/views/creatives/_form.html.slim
= f.fields_for :attachments do |attachment|
- if attachment.object.persisted?
= image_tag attachment.object.file_url(:thumb)
| Remove?
= attachment.check_box :_destroy
- else
= attachment.label :file
= attachment.hidden_field :file, value: attachment.object.cached_file_data
= attachment.file_field :file
Attacher.validate do
kind = record.creative.kind # record returns the #<Attachment> instance
#...
end
Advertencia legal: Este mensaje y, en su caso, los ficheros anexos son confidenciales, especialmente en lo que respecta a los datos personales, y se dirigen exclusivamente al destinatario referenciado. Si usted no lo es y lo ha recibido por error o tiene conocimiento del mismo por cualquier motivo, le rogamos que nos lo comunique por este medio y proceda a destruirlo o borrarlo, y que en todo caso se abstenga de utilizar, reproducir, alterar, archivar o comunicar a terceros el presente mensaje y ficheros anexos, todo ello bajo pena de incurrir en responsabilidades legales. El emisor no garantiza la integridad, rapidez o seguridad del presente correo, ni se responsabiliza de posibles perjuicios derivados de la captura, incorporaciones de virus o cualesquiera otras manipulaciones efectuadas por terceros.
Disclaimer: This message and any attached files transmitted with it, is confidential, especially as regards personal data. It is intended solely for the use of the individual or entity to whom it is addressed. If you are not the intended recipient and have received this information in error or have accessed it for any reason, please notify us of this fact by email reply and then destroy or delete the message, refraining from any reproduction, use, alteration, filing or communication to third parties of this message and attached files on penalty of incurring legal responsibilities. The sender does not guarantee the integrity, the accuracy, the swift delivery or the security of this email transmission, and assumes no responsibility for any possible damage incurred through data capture, virus incorporation or any manipulation carried out by third parties.
--
You received this message because you are subscribed to the Google Groups "Shrine" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-shrine+unsubscribe@googlegroups.com.
To post to this group, send email to ruby-...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ruby-shrine/470aafe3-3126-4b78-b1cb-e6ba20a9206a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-shrine...@googlegroups.com.
class Attachment < ActiveRecord::Base
attr_accessor :kind
end
# app/views/creatives/_form.html.slim
= f.fields_for :attachments do |attachment|
- if attachment.object.persisted?
= image_tag attachment.object.file_url(:thumb)
| Remove?
= attachment.check_box :_destroy
- else
= attachment.label :file
= attachment.hidden_filed :kind, value: creative_kind.name # <== new field
= attachment.hidden_field :file, value: attachment.object.cached_file_data
= attachment.file_field :file
Attacher.validate do
case record.kind
when "Image" # ...
when "HTML" # ...
when "Dynamic" # ...
end
end
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-shrine+unsubscribe@googlegroups.com.
To post to this group, send email to ruby-...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ruby-shrine/03b23cd7-87f0-4f5e-a692-526d224e62df%40googlegroups.com.
To unsubscribe from this group and stop receiving emails from it, send an email to ruby-shrine+unsubscribe@googlegroups.com.
To post to this group, send email to ruby-...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ruby-shrine/29cb36a4-36e6-4aaf-aa66-900a49d80b32%40googlegroups.com.