view app/controllers/pastes_controller.rb @ 325:45bf99bfd48b

Remove authenticity token from form.
author edogawaconan <me@myconan.net>
date Sun, 06 Apr 2014 18:25:59 +0900
parents fec39456dcbe
children 430dadffd91e
line wrap: on
line source

class PastesController < ApplicationController
  before_action :lowercase_path, :only => :show

  # GET /1
  # GET /1.txt
  def show
    @paste = Paste.safe_find(params[:id])
    head :not_found and return unless @paste

    respond_to do |format|
      format.html { cache }
      format.txt { cache }
    end
  end

  # GET /
  def new
    @paste = Paste.new
    @paste.set_paste_key
    @paste.paste = Paste.safe_find(params[:base]).try(:paste)

    respond_to do |format|
      format.html # new.html.erb
    end
  end

  # POST /
  # POST /pastes.json
  # POST /pastes.txt
  def create
    @paste = Paste.new(paste_params.merge(ip: request.remote_ip))

    begin
      respond_to do |format|
        if @paste.save
          @fresh = true
          format.html { redirect_to @paste, :notice => 'Paste was successfully created.' }
          format.json { render :json => @paste, :status => :created, :location => @paste }
        else
          flash.now[:alert] = @paste.errors.full_messages.to_sentence
          format.html { render :action => "new" }
          format.json { render :json => @paste.errors, :status => :unprocessable_entity }
        end
        format.txt
      end
    rescue ActiveRecord::RecordNotUnique
      @paste = Paste.where(:ip => @paste.ip, :paste_hash => @paste.paste_hash).first
      respond_to do |format|
        format.html { redirect_to paste_path(@paste) }
        format.json { render :json => @paste }
        format.txt
      end
    end
  end

  def destroy
    @paste = Paste.safe_find(params[:id])
    if @paste.safe_destroy(params[:paste][:key])
      uncache
      redirect_to root_path, :notice => "Paste ##{params[:id]} deleted"
    else
      flash.now[:alert] = @paste.errors.full_messages.to_sentence
      render :show
    end
  end

  private

  def lowercase_path
    correct_path = request.fullpath.downcase
    redirect_to correct_path, :status => :moved_permanently  unless
      correct_path == request.fullpath
  end

  def cache_key(format = request.format.symbol)
    ext = case format
          when :txt
            ".txt"
          when :html, nil
            ""
          else
            ".unknown"
          end
    "pastes:#{@paste.to_param}#{ext}"
  end

  def cache
    Rails.cache.fetch cache_key, :raw => true do
      render_to_string :show
    end
  end

  def uncache
    [:txt, :html, :unknown].each do |format|
      Rails.cache.delete cache_key(format)
    end
  end

  def paste_params
    params.require(:paste).permit(:paste, :paste_gzip, :paste_gzip_base64, :is_private, :key)
  end
end