Files
nairobi/app/models/direct_upload.rb
Javi Martín db97f9d08c Add and apply rubocop rules for empty lines
We were very inconsistent regarding these rules.

Personally I prefer no empty lines around blocks, clases, etc... as
recommended by the Ruby style guide [1], and they're the default values
in rubocop, so those are the settings I'm applying.

The exception is the `private` access modifier, since we were leaving
empty lines around it most of the time. That's the default rubocop rule
as well. Personally I don't have a strong preference about this one.


[1] https://rubystyle.guide/#empty-lines-around-bodies
2019-10-24 17:11:47 +02:00

66 lines
2.0 KiB
Ruby

class DirectUpload
include ActiveModel::Validations
include ActiveModel::Conversion
extend ActiveModel::Naming
attr_accessor :resource, :resource_type, :resource_id,
:relation, :resource_relation,
:attachment, :cached_attachment, :user
validates :attachment, :resource_type, :resource_relation, :user, presence: true
validate :parent_resource_attachment_validations,
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)
# Refactor
@relation = if @resource.respond_to?(:images) &&
((@attachment.present? && !@attachment.content_type.match(/pdf/)) || @cached_attachment.present?)
@resource.images.send("build", relation_attributtes)
elsif @resource.class.reflections[@resource_relation].macro == :has_one
@resource.send("build_#{resource_relation}", relation_attributtes)
else
@resource.send(@resource_relation).build(relation_attributtes)
end
@relation.user = user
end
end
def save_attachment
@relation.attachment.save
end
def destroy_attachment
@relation.attachment.destroy
end
def persisted?
false
end
private
def parent_resource_attachment_validations
@relation.valid?
if @relation.errors.key? :attachment
errors.add(:attachment, @relation.errors.full_messages_for(:attachment))
end
end
def relation_attributtes
{
attachment: @attachment,
cached_attachment: @cached_attachment,
user: @user
}
end
end