2019-08-06 23:17:29 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
# La relación de un sitio con sus artículos, esto nos permite generar
|
|
|
|
# artículos como si estuviésemos usando ActiveRecord.
|
|
|
|
class PostRelation < Array
|
|
|
|
# No necesitamos cambiar el sitio
|
|
|
|
attr_reader :site
|
|
|
|
|
|
|
|
def initialize(site:)
|
|
|
|
@site = site
|
|
|
|
# Proseguimos la inicialización sin valores por defecto
|
|
|
|
super()
|
|
|
|
end
|
|
|
|
|
|
|
|
# Genera un artículo nuevo con los parámetros que le pasemos y lo suma
|
|
|
|
# al array
|
|
|
|
def build(**args)
|
2019-08-08 19:26:47 +00:00
|
|
|
args[:lang] ||= I18n.locale
|
2019-09-17 21:27:51 +00:00
|
|
|
args[:document] ||= build_document(collection: args[:lang])
|
2019-08-08 19:26:47 +00:00
|
|
|
args[:layout] = build_layout(args[:layout])
|
|
|
|
|
|
|
|
post = Post.new(site: site, **args)
|
|
|
|
|
|
|
|
self << post
|
|
|
|
post
|
2019-08-06 23:17:29 +00:00
|
|
|
end
|
|
|
|
|
2019-09-16 17:56:34 +00:00
|
|
|
def create(**args)
|
|
|
|
post = build(args)
|
|
|
|
post.save
|
|
|
|
post
|
|
|
|
end
|
|
|
|
|
2019-09-17 21:27:51 +00:00
|
|
|
alias find_generic find
|
|
|
|
|
2019-08-14 21:19:01 +00:00
|
|
|
def find(id)
|
2019-09-17 21:27:51 +00:00
|
|
|
find_generic do |p|
|
2019-08-14 21:19:01 +00:00
|
|
|
p.id == id
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2019-09-17 21:27:51 +00:00
|
|
|
# Encuentra el primer post por el valor de un atributo
|
|
|
|
# XXX: Acepta cualquier atributo
|
|
|
|
def find_by(**args)
|
|
|
|
find_generic do |p|
|
|
|
|
p.public_send(args.first.first).try(:value) == args.first.last
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2019-08-06 23:17:29 +00:00
|
|
|
# Intenta guardar todos y devuelve true si pudo
|
|
|
|
def save_all
|
|
|
|
map(&:save).all?
|
|
|
|
end
|
2019-08-08 19:26:47 +00:00
|
|
|
|
|
|
|
private
|
|
|
|
|
2019-08-13 19:09:23 +00:00
|
|
|
def build_layout(layout = nil)
|
2019-08-08 19:26:47 +00:00
|
|
|
return layout if layout.is_a? Layout
|
|
|
|
|
2019-08-13 19:09:23 +00:00
|
|
|
site.layouts[layout || :post]
|
2019-08-08 19:26:47 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# Devuelve una colección Jekyll que hace pasar el documento
|
2019-09-17 21:27:51 +00:00
|
|
|
def build_collection(label:)
|
|
|
|
Jekyll::Collection.new(site.jekyll, label.to_s)
|
2019-08-08 19:26:47 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
# Un documento borrador con algunas propiedades por defecto
|
2019-09-17 21:27:51 +00:00
|
|
|
def build_document(collection:)
|
|
|
|
col = build_collection(label: collection)
|
|
|
|
doc = Jekyll::Document.new('', site: site.jekyll, collection: col)
|
2019-08-08 19:26:47 +00:00
|
|
|
doc.data['date'] = Date.today.to_time
|
|
|
|
doc
|
|
|
|
end
|
2019-08-06 23:17:29 +00:00
|
|
|
end
|