class PostsController < ApplicationController include Pundit before_action :authenticate! def index @site = find_site authorize @site @lang = find_lang(@site) @category = session[:category] = params.dig(:category) @posts = policy_scope(@site.posts_for(@lang), policy_scope_class: PostPolicy::Scope) if params[:sort_by].present? begin @posts.sort_by! do |p| p.send(params[:sort_by].to_s) end rescue ArgumentError end end end def show @site = find_site @lang = find_lang(@site) @post = find_post(@site) authorize @post end def new authorize Post @site = find_site @lang = find_lang(@site) @template = find_template(@site) @post = Post.new(site: @site, front_matter: { date: Time.now }, lang: @lang, template: @template) end def create authorize Post @site = find_site @lang = find_lang(@site) @template = find_template(@site) @post = Post.new(site: @site, lang: @lang, template: @template) @post.update_attributes(repair_nested_params(post_params)) # Las usuarias pueden especificar una autora, de la contrario por # defecto es la usuaria actual if current_user.is_a? Usuaria @post.update_attributes({author: params[:post][:author]}) else # Todo lo que crean lxs invitadxs es borrador @post.update_attributes({draft: true}) end @post.update_attributes({author: current_user.username}) unless @post.author if @post.save flash[:success] = @site.config.dig('thanks') redirect_to site_posts_path(@site, lang: @lang) else render 'posts/new' end end def edit @site = find_site @lang = find_lang(@site) @post = find_post(@site) authorize @post end def update @site = find_site @lang = find_lang(@site) @post = find_post(@site) authorize @post @post.update_attributes(repair_nested_params(post_params)) # Solo las usuarias pueden modificar la autorĂ­a if current_user.is_a? Usuaria @post.update_attributes({author: params[:post][:author]}) if params[:post][:author].present? @post.update_attributes({draft: false}) else # Todo lo que crean lxs invitadxs es borrador @post.update_attributes({draft: true}) end if @post.save flash[:success] = @site.config.dig('thanks') redirect_to site_posts_path(@site, category: session[:category], lang: @lang) else render 'posts/edit' end end private # Solo permitir cambiar estos atributos de cada articulo def post_params params.require(:post).permit(@post.template_params) end # https://gist.github.com/bloudermilk/2884947#gistcomment-1915521 def repair_nested_params(obj) obj.each do |key, value| if value.is_a?(ActionController::Parameters) || value.is_a?(Hash) # If any non-integer keys if value.keys.find {|k, _| k =~ /\D/ } repair_nested_params(value) else obj[key] = value.values obj[key].each {|h| repair_nested_params(h) } end end end end end