mirror of
https://0xacab.org/sutty/sutty
synced 2024-07-08 23:35:45 +00:00
70 lines
1.3 KiB
Ruby
70 lines
1.3 KiB
Ruby
![]() |
# frozen_string_literal: true
|
||
|
|
||
|
require 'yaml'
|
||
|
|
||
|
module Sutty
|
||
|
module Models
|
||
|
# Un post
|
||
|
class Post
|
||
|
attr_accessor :content, :front_matter
|
||
|
attr_reader :post, :site
|
||
|
|
||
|
REJECT_FROM_DATA = %w[excerpt slug draft date ext].freeze
|
||
|
|
||
|
def initialize(site, post = nil)
|
||
|
@site = site
|
||
|
@post = post
|
||
|
end
|
||
|
|
||
|
def new?
|
||
|
!@post.is_a? Jekyll::Document
|
||
|
end
|
||
|
|
||
|
def save
|
||
|
front_matter_from_data!
|
||
|
clean_content!
|
||
|
|
||
|
return unless write.zero?
|
||
|
|
||
|
@post.read
|
||
|
true
|
||
|
end
|
||
|
|
||
|
private
|
||
|
|
||
|
def front_matter_from_data!
|
||
|
@front_matter ||= @post.data.reject do |key, _|
|
||
|
REJECT_FROM_DATA.include? key
|
||
|
end
|
||
|
end
|
||
|
|
||
|
# Aplica limpiezas básicas del contenido
|
||
|
def clean_content!
|
||
|
@content = @content.delete("\r")
|
||
|
end
|
||
|
|
||
|
def write
|
||
|
File.open(@post.path, 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)
|
||
|
|
||
|
# Empezar por el principio
|
||
|
f.rewind
|
||
|
|
||
|
# Escribir
|
||
|
f.write(full_content)
|
||
|
|
||
|
# Eliminar el resto
|
||
|
f.flush
|
||
|
f.truncate(f.pos)
|
||
|
end
|
||
|
end
|
||
|
|
||
|
def full_content
|
||
|
"#{@front_matter.to_yaml}---\n\n#{@content}"
|
||
|
end
|
||
|
end
|
||
|
end
|
||
|
end
|