5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-07-02 12:46:07 +00:00
panel/app/services/post_service.rb

89 lines
2.4 KiB
Ruby
Raw Normal View History

2019-08-13 23:33:57 +00:00
# frozen_string_literal: true
# Este servicio se encarga de crear artículos y guardarlos en git,
# asignándoselos a une usuarie
# rubocop:disable Metrics/BlockLength
2019-08-13 23:33:57 +00:00
PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do
# Crea un artículo nuevo
#
# @return Post
def create
2019-11-15 16:35:27 +00:00
self.post = site.posts(lang: params[:post][:lang] || I18n.locale)
.build(layout: params[:post][:layout])
post.usuaries << usuarie
params[:post][:draft] = true if site.invitade? usuarie
commit(action: :created) if post.update(post_params)
# Devolver el post aunque no se haya salvado para poder rescatar los
# errores
post
end
def update
post.usuaries << usuarie
params[:post][:draft] = true if site.invitade? usuarie
commit(action: :updated) if post.update(post_params)
2019-08-13 23:33:57 +00:00
# Devolver el post aunque no se haya salvado para poder rescatar los
# errores
post
end
2019-08-16 23:12:22 +00:00
def destroy
post.destroy!
commit(action: :destroyed) if post.destroyed?
2019-08-16 23:12:22 +00:00
post
end
2019-11-06 22:35:48 +00:00
# Reordena todos los posts que soporten orden de acuerdo a un hash de
# ids y nuevas posiciones. La posición actual la da la posición en
2019-10-18 20:35:09 +00:00
# el array.
#
2019-11-06 22:35:48 +00:00
# { sha1 => 2, sha1 => 1, sha1 => 0 }
2019-10-18 20:35:09 +00:00
def reorder
posts = site.posts(lang: lang)
2019-11-06 22:35:48 +00:00
reorder = params.require(:post).permit(reorder: {}).try(:[], :reorder)
modified = PostRelation.new(site: site)
2019-10-18 20:35:09 +00:00
2019-11-06 22:35:48 +00:00
files = reorder.keys.map do |id|
post = posts.find(id, sha1: true)
order = reorder[id].to_i
2019-10-18 20:35:09 +00:00
next unless post.attributes.include? :order
next if post.order.value == order
2019-10-18 20:35:09 +00:00
modified << post
post.order.value = order
2019-10-18 20:35:09 +00:00
post.path.absolute
end.compact
# TODO: Implementar transacciones!
modified.save_all(validate: false) &&
commit(action: :reorder, file: files)
2019-10-18 20:35:09 +00:00
end
2019-08-13 23:33:57 +00:00
private
2019-10-18 20:35:09 +00:00
def commit(action:, file: nil)
site.repository.commit(file: file || post.path.absolute,
usuarie: usuarie,
2019-08-16 23:12:22 +00:00
remove: action == :destroyed,
message: I18n.t("post_service.#{action}",
2019-10-18 20:35:09 +00:00
title: post.try(:title).try(:value)))
end
2019-08-13 23:33:57 +00:00
# Solo permitir cambiar estos atributos de cada articulo
def post_params
params.require(:post).permit(post.params)
end
2019-10-18 20:35:09 +00:00
def lang
params[:post][:lang] || I18n.locale
end
2019-08-13 23:33:57 +00:00
end
# rubocop:enable Metrics/BlockLength