Stronger direct upload model specs

This commit is contained in:
Senén Rodero Rodríguez
2017-09-20 18:22:52 +02:00
parent 346c329919
commit 661bdda41f
6 changed files with 79 additions and 52 deletions

View File

@@ -7,9 +7,27 @@ class DirectUpload
:relation, :resource_relation,
:attachment, :cached_attachment, :user
validates_presence_of :attachment, :resource_type, :resource_relation
validates_presence_of :attachment, :resource_type, :resource_relation, :user
validate :parent_resource_attachment_validations,
if: -> { attachment.present? && resource_type.present? && resource_relation.present? }
if: -> { attachment.present? && resource_type.present? && resource_relation.present? && user.present? }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
if @resource_type.present? && @resource_relation.present? && (@attachment.present? || @cached_attachment.present?)
@resource = @resource_type.constantize.find_or_initialize_by(id: @resource_id)
if @resource.class.reflections[@resource_relation].macro == :has_one
@relation = @resource.send("build_#{resource_relation}", relation_attributtes)
else
@relation = @resource.send(@resource_relation).build(relation_attributtes)
end
@relation.user = user
end
end
def save_attachment
@relation.attachment.save
@@ -23,24 +41,6 @@ class DirectUpload
false
end
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
if @resource_type.present?
@resource = @resource_type.constantize.find_or_initialize_by(id: @resource_id)
end
if @resource.class.reflections[@resource_relation].macro == :has_one
@relation = @resource.send("build_#{resource_relation}", attachment: @attachment, cached_attachment: @cached_attachment)
else
@relation = @resource.send(resource_relation).build(attachment: @attachment, cached_attachment: @cached_attachment)
end
@relation.user = user
end
private
def parent_resource_attachment_validations
@@ -51,4 +51,12 @@ class DirectUpload
end
end
def relation_attributtes
{
attachment: @attachment,
cached_attachment: @cached_attachment,
user: @user
}
end
end