# frozen_string_literal: true # Controlador para artículos class PostsController < ApplicationController include Pundit before_action :authenticate_usuarie! def index authorize Post @site = find_site @category = session[:category] = params.dig(:category) @layout = params.dig(:layout).try :to_sym # XXX: Cada vez que cambiamos un Post tocamos el sitio con lo que es # más simple saber si hubo cambios. if @category || @layout || stale?(@site) # TODO: Aplicar policy_scope @posts = @site.posts(lang: lang) @posts.sort_by!(:order, :date).reverse! @usuarie = @site.usuarie? current_usuarie end end def show @site = find_site @post = @site.posts(lang: lang).find params[:id] authorize @post fresh_when @post end def new authorize Post @site = find_site @post = @site.posts.build(lang: lang, layout: params[:layout]) end def create authorize Post @site = find_site service = PostService.new(site: @site, usuarie: current_usuarie, params: params) if (@post = service.create.persisted?) @site.touch redirect_to site_posts_path(@site) else render 'posts/new' end end def edit @site = find_site @post = @site.posts(lang: lang).find params[:id] authorize @post end def update @site = find_site @post = @site.posts(lang: lang).find params[:id] authorize @post service = PostService.new(site: @site, post: @post, usuarie: current_usuarie, params: params) if service.update.persisted? @site.touch redirect_to site_posts_path(@site) else render 'posts/edit' end end # Eliminar artículos def destroy @site = find_site @post = @site.posts(lang: lang).find params[:id] authorize @post service = PostService.new(site: @site, post: @post, usuarie: current_usuarie, params: params) # TODO: Notificar si se pudo o no service.destroy @site.touch redirect_to site_posts_path(@site) end # Reordenar los artículos def reorder @site = find_site authorize @site service = PostService.new(site: @site, usuarie: current_usuarie, params: params) service.reorder @site.touch redirect_to site_posts_path(@site) end # Devuelve el idioma solicitado a través de un parámetro, validando # que el sitio soporte ese idioma def lang return unless params[:lang] return unless @site.try(:locales).try(:include?, params[:lang]) params[:lang] end end