diff --git a/app/models/metadata_path.rb b/app/models/metadata_path.rb index c3c0e15..efb7baf 100644 --- a/app/models/metadata_path.rb +++ b/app/models/metadata_path.rb @@ -14,7 +14,7 @@ class MetadataPath < MetadataTemplate alias to_s value def relative - value.sub(site.path, '').sub(%r{^/}, '') + Pathname.new(value).relative_path_from(Pathname.new(site.path)).to_s end private diff --git a/app/models/metadata_slug.rb b/app/models/metadata_slug.rb index 75dbadf..e37d123 100644 --- a/app/models/metadata_slug.rb +++ b/app/models/metadata_slug.rb @@ -41,6 +41,6 @@ class MetadataSlug < MetadataTemplate def title return if post.title.try(:value).blank? - post.title.try(:value).blank? + post.title.try(:value) end end diff --git a/app/models/post.rb b/app/models/post.rb index 23e5dff..86a0d05 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -188,57 +188,12 @@ class Post < OpenStruct end alias validate! validate - # Solo agregar el post al sitio una vez que lo guardamos - # - # TODO no sería la forma correcta de hacerlo en Rails - # def add_post_to_site! - # @site.jekyll.collections[@collection].docs << @post - # @site.jekyll.collections[@collection].docs.sort! - - # unless @site.collections[@collection].include? self - # @site.collections[@collection] << self - # @site.collections[@collection].sort! - # end - # end - - # Cambiar el nombre del archivo si cambió el título o la fecha. - # Como Jekyll no tiene métodos para modificar un Document, lo - # engañamos eliminando la instancia de @post y recargando otra. - def detect_file_rename! - return true unless basename_changed? - # No eliminamos el archivo a menos que ya exista el reemplazo! - return false unless File.exist? path - - Rails.logger.info I18n.t('posts.logger.rm', path: path) - FileUtils.rm @post.path - # replace_post! - end - - # Reemplaza el post en el sitio por uno nuevo - # TODO: refactorizar - # def replace_post! - # @old_post = @site.jekyll.collections[@lang].docs.delete @post - - # new_post - # end - # Guarda los cambios en el archivo destino def write return true if persisted? Site::Writer.new(site: site, file: path.absolute, - content: full_content, usuarie: usuarie, - message: title.value).save - end - - # Devuelve le autore de un artículo - # XXX: Si se cambia le autore en el editor también cambia quién hace - # un cambio y se le puede asignar a cualquier otre. - # TODO: Mover la escritura a un servicio que combine escritura, commit - # y current_usuarie - def usuarie - OpenStruct.new(email: author.value.first, - name: author.value.first.split('@', 2).first) + content: full_content).save end # Verifica si hace falta escribir cambios diff --git a/app/models/post_relation.rb b/app/models/post_relation.rb index e19976c..060a914 100644 --- a/app/models/post_relation.rb +++ b/app/models/post_relation.rb @@ -35,7 +35,7 @@ class PostRelation < Array def build_layout(layout = :post) return layout if layout.is_a? Layout - site.layouts[symbol] + site.layouts[layout] end # Devuelve una colección Jekyll que hace pasar el documento diff --git a/app/models/site/writer.rb b/app/models/site/writer.rb index f9350f1..eb0ccc3 100644 --- a/app/models/site/writer.rb +++ b/app/models/site/writer.rb @@ -1,46 +1,29 @@ # frozen_string_literal: true -class Site - # Se encarga de guardar los cambios en los archivos y mantenerlos - # actualizados en git - class Writer - attr_reader :site, :file, :content, :usuarie, :message +# Se encarga de guardar los cambios en los archivos y mantenerlos +# actualizados en git +Site::Writer = Struct.new(:site, :file, :content, keyword_init: true) do + # TODO: si el archivo está bloqueado, esperar al desbloqueo + def save + File.open(file, File::RDWR | File::CREAT, 0o640) do |f| + # Bloquear el archivo para que no sea accedido por otro + # proceso u otre editore + f.flock(File::LOCK_EX) - def initialize(site:, file:, content:, usuarie:, message:) - @site = site - @content = content - @file = file - @usuarie = usuarie - @message = message - end + # Empezar por el principio + f.rewind - # rubocop:disable Metrics/AbcSize - def save - r = File.open(file, File::RDWR | File::CREAT, 0o640) do |f| - # Bloquear el archivo para que no sea accedido por otro - # proceso u otra editora - f.flock(File::LOCK_EX) + # Escribir el contenido + f.write(content) - # Empezar por el principio - f.rewind + # Eliminar el resto + f.flush + f.truncate(f.pos) + end.zero? + end - # Escribir el contenido - f.write(content) - - # Eliminar el resto - f.flush - f.truncate(f.pos) - end - - r.zero? && site.repository.commit(file: relative_file, - usuarie: usuarie, - message: message) - end - # rubocop:enable Metrics/AbcSize - - # Devuelve la ruta relativa a la raíz del sitio - def relative_file - Pathname.new(file).relative_path_from(Pathname.new(site.path)).to_s - end + # Devuelve la ruta relativa a la raíz del sitio + def relative_file + Pathname.new(file).relative_path_from(Pathname.new(site.path)).to_s end end diff --git a/config/locales/en.yml b/config/locales/en.yml index 193c056..4d974f6 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1,4 +1,6 @@ en: + post_service: + created: 'Created "%{title}"' metadata: array: cant_be_empty: 'This field cannot be empty' diff --git a/config/locales/es.yml b/config/locales/es.yml index e0de4d2..6298d74 100644 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -1,4 +1,6 @@ es: + post_service: + created: 'Creado "%{title}"' metadata: array: cant_be_empty: 'El campo no puede estar vacío' diff --git a/doc/posts.md b/doc/posts.md index 2461a90..ddb1fbb 100644 --- a/doc/posts.md +++ b/doc/posts.md @@ -97,6 +97,4 @@ Al instanciar un `Post`, se pasan el sitio y la plantilla por defecto. * Reimplementar glosario (se crea un artículo por cada categoría utilizada) * Reimplementar orden de artículos (ver doc) -* Detectar cambio de nombre (fecha y slug) -* Crear artículos nuevos * Convertir layout a params diff --git a/test/models/post_test.rb b/test/models/post_test.rb index c33e75b..a5236f1 100644 --- a/test/models/post_test.rb +++ b/test/models/post_test.rb @@ -18,10 +18,7 @@ class PostTest < ActiveSupport::TestCase test 'se puede acceder a los valores' do assert @site.posts.size.positive? - - assert @post.categories.values.size.positive? - assert @post.tags.values.size.positive? - assert @post.title.size.positive? + assert @post.title.value.size.positive? assert @post.content.size.positive? end @@ -168,5 +165,6 @@ class PostTest < ActiveSupport::TestCase assert post.new? assert post.save + assert File.exist?(post.path.absolute) end end