# 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 PostService = Struct.new(:site, :usuarie, :post, :params, keyword_init: true) do # Crea un artículo nuevo # # @return Post def create # TODO: Implementar layout self.post = site.posts(lang: params[:post][:lang] || I18n.locale).build 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) # Devolver el post aunque no se haya salvado para poder rescatar los # errores post end def destroy post.destroy! commit(action: :destroyed) if post.destroyed? post end # Reordena todos los posts que soporten orden de acuerdo a un array # con las nuevas posiciones. La posición actual la da la posición en # el array. # # [ 1, 0, 2 ] => mover el elemento 2 a la posición 1, mantener 3 def reorder posts = site.posts(lang: lang) reorder = params.require(:post).permit(reorder: []) .try(:[], :reorder) .try(:map, &:to_i) || [] # Tenemos que pasar un array con la misma cantidad de elementos return false if reorder.size != posts.size files = reorder.map.with_index do |new, cur| post = posts[cur] next unless post.attributes.include? :order post.usuaries << usuarie post.order.value = new post.path.absolute end.compact # TODO: Implementar transacciones! posts.save_all && commit(action: :reorder, file: files) end private def commit(action:, file: nil) site.repository.commit(file: file || post.path.absolute, usuarie: usuarie, remove: action == :destroyed, message: I18n.t("post_service.#{action}", title: post.try(:title).try(:value))) end # Solo permitir cambiar estos atributos de cada articulo def post_params params.require(:post).permit(post.params) end def lang params[:post][:lang] || I18n.locale end end # rubocop:enable Metrics/BlockLength