5
0
Fork 0
mirror of https://0xacab.org/sutty/sutty synced 2024-07-04 00:05:45 +00:00

wip de i18n

This commit is contained in:
f 2018-02-22 16:01:11 -03:00
parent 9b02872ed6
commit 5ec7c45861
No known key found for this signature in database
GPG key ID: F3FDAB97B5F9F7E7
5 changed files with 100 additions and 29 deletions

View file

@ -22,8 +22,10 @@ class ApplicationController < ActionController::Base
def find_post(site) def find_post(site)
id = params[:post_id] || params[:id] id = params[:post_id] || params[:id]
lang = params.fetch(:lang, I18n.locale.to_s)
posts = site.posts_for(lang)
site.posts.find do |p| posts.find do |p|
p.id == id p.id == id
end end
end end

View file

@ -2,8 +2,10 @@ class PostsController < ApplicationController
before_action :authenticate! before_action :authenticate!
def index def index
@site = find_site @site = find_site
@category = session[:category] = params.dig(:category) @category = session[:category] = params.dig(:category)
@lang = params.fetch(:lang, I18n.locale.to_s)
@posts = @site.posts_for(@lang)
end end
def show def show

View file

@ -15,7 +15,7 @@ require 'jekyll/utils'
# datos y los sincroniza al momento de leer y de escribir el Document. # datos y los sincroniza al momento de leer y de escribir el Document.
class Post class Post
attr_accessor :content, :front_matter attr_accessor :content, :front_matter
attr_reader :post, :site, :errors, :old_post attr_reader :post, :site, :errors, :old_post, :lang
REJECT_FROM_DATA = %w[excerpt].freeze REJECT_FROM_DATA = %w[excerpt].freeze
# datos que no tienen que terminar en el front matter # datos que no tienen que terminar en el front matter
@ -24,7 +24,7 @@ class Post
# Trabajar con posts. Si estamos creando uno nuevo, el **site** y # Trabajar con posts. Si estamos creando uno nuevo, el **site** y
# el **front_matter** son necesarios, sino, **site** y **post**. # el **front_matter** son necesarios, sino, **site** y **post**.
# XXX chequear que se den las condiciones # XXX chequear que se den las condiciones
def initialize(site:, post: nil, front_matter: {}) def initialize(site:, post: nil, front_matter: {}, lang: nil)
unless site.is_a?(Site) unless site.is_a?(Site)
raise ArgumentError, raise ArgumentError,
I18n.t('errors.argument_error', argument: :site, class: Site) I18n.t('errors.argument_error', argument: :site, class: Site)
@ -36,6 +36,7 @@ class Post
class: Jekyll::Document) class: Jekyll::Document)
end end
@lang = lang || I18n.locale.to_s
@site = site @site = site
@post = post @post = post
# los errores tienen que ser un hash para que # los errores tienen que ser un hash para que
@ -62,6 +63,21 @@ class Post
@post.nil? || !File.exist?(@post.try(:path)) @post.nil? || !File.exist?(@post.try(:path))
end end
# Determina si fue traducido, buscando los slugs de su front_matter
# lang en otras colecciones
def translated?
get_front_matter('lang').present?
end
def translations
@translations ||= get_front_matter('lang').map do |lang, id|
next if lang == @lang
@site.posts_for(lang).find do |p|
p.id == id
end
end.compact
end
# Guarda los cambios. # Guarda los cambios.
# #
# Recién cuando vamos a guardar creamos el Post, porque ya tenemos # Recién cuando vamos a guardar creamos el Post, porque ya tenemos

View file

@ -10,11 +10,20 @@ class Site
@path = path || @jekyll.config['source'] @path = path || @jekyll.config['source']
end end
# Determina si el sitio está en varios idiomas
def i18n?
@jekyll.config.dig('i18n').present?
end
# Obtener el nombre del sitio # Obtener el nombre del sitio
def name def name
@name ||= @jekyll.config['source'].split('/').last @name ||= @jekyll.config['source'].split('/').last
end end
def name_with_i18n(lang)
[name, lang].join('/')
end
# El id es el sitio sin puntos, para no confundir al routeador de # El id es el sitio sin puntos, para no confundir al routeador de
# rails # rails
def id def id
@ -50,16 +59,32 @@ class Site
end end
@jekyll.config @jekyll.config
end end
# Los posts de este sitio # Los posts de este sitio, si el sitio está traducido, trae los posts
# del idioma actual, porque _posts va a estar vacío
def posts def posts
return @posts if @posts @posts ||= if i18n?
posts_for(I18n.locale.to_s)
else
posts_for('posts')
end
end
Rails.logger.info 'Procesando posts' # Obtiene todos los posts de una colección determinada
#
# Devuelve nil si la colección no existe
def posts_for(collection)
return unless @jekyll.config['collections'].key? collection
if @jekyll.posts.docs.empty? # TODO tal vez no necesitamos esta magia
instance = instance_variable_get("@#{collection}")
return instance if instance
Rails.logger.info "Procesando #{collection}"
col = @jekyll.collections[collection].docs
if col.empty?
@jekyll.read @jekyll.read
# Queremos saber cuantas veces releemos los articulos # Queremos saber cuantas veces releemos los articulos
Rails.logger.info 'Leyendo articulos' Rails.logger.info 'Leyendo articulos'
@ -67,9 +92,9 @@ class Site
# Los convertimos a una clase intermedia capaz de acceder a sus # Los convertimos a una clase intermedia capaz de acceder a sus
# datos y modificarlos # datos y modificarlos
@posts = @jekyll.posts.docs.map do |post| instance_variable_set("@#{collection}", col.map do |post|
Post.new(site: self, post: post) Post.new(site: self, post: post, lang: collection)
end end)
end end
def categories def categories
@ -188,6 +213,15 @@ class Site
config[unneeded] = [] if config.key? unneeded config[unneeded] = [] if config.key? unneeded
end end
# Si estamos usando nuestro propio plugin de i18n, los posts están
# en "colecciones"
i18n = config.dig('i18n')
if i18n
i18n.each do |i|
config['collections'][i] = {}
end
end
Jekyll::Site.new(config) Jekyll::Site.new(config)
end end

View file

@ -1,9 +1,10 @@
.row .row
.col .col
= render 'layouts/breadcrumb', crumbs: [ link_to(t('sites.index'), sites_path), @site.name, link_to(t('posts.index'), site_posts_path(@site)), @category ] = render 'layouts/breadcrumb',
crumbs: [ link_to(t('sites.index'), sites_path), @site.name, link_to(t('posts.index'), site_posts_path(@site)), @category ]
.row .row
.col .col
%h1= @site.name %h1= @site.name_with_i18n(@lang)
.row .row
.col .col
@ -12,18 +13,34 @@
.row .row
.col .col
%table.table.table-condensed.table-striped - if @posts.present?
%tbody %table.table.table-condensed.table-striped
- @site.posts.each do |post| %tbody
- if @category - @posts.each do |post|
- next unless post.categories.include?(@category) - if @category
- direction = post.get_front_matter(:dir) -# saltearse el post a menos que esté en la categoría
%tr -# por la que estamos filtrando
%td{class: direction} - next unless post.categories.include?(@category)
= link_to post.title, site_post_path(@site, post) -# establecer la direccion del texto
%br - direction = post.get_front_matter(:dir)
%small %tr
- post.categories.each do |c| %td{class: direction}
= link_to c, site_posts_path(@site, category: c) = link_to post.title, site_post_path(@site, post)
%td= post.date.strftime('%F') %br
%td= link_to t('post.edit'), edit_site_post_path(@site, post) %small
- post.categories.each do |c|
= link_to c, site_posts_path(@site, category: c)
%td
- if post.translations
%small
- post.translations.each do |pt|
= link_to pt.title, site_post_path(@site, pt, lang: pt.lang)
%span.badge.badge-info= t("i18n.#{pt.lang}")
%br
%td= post.date.strftime('%F')
%td= link_to t('post.edit'),
edit_site_post_path(@site, post),
class: 'btn btn-info'
- else
%h2= t('posts.none')