view app/controllers/pastes_controller.rb @ 192:1da19a81f5d7

Update rails to 3.2.13 and various other gems.
author Edho Arief <edho@myconan.net>
date Wed, 20 Mar 2013 04:55:49 +0900
parents 4e409ac7082d
children 5e1d728975a4
line wrap: on
line source

class PastesController < ApplicationController
  caches_page :show

  # GET /1
  # GET /1.txt
  def show
    id = params[:id].to_i
    if id.to_s != params[:id]
      redirect_to paste_path(id)
      return
    end
    @paste = Paste.find(params[:id])

    expires_in 1.year, :public => true
    respond_to do |format|
      format.html # show.html.erb
      format.txt # show.txt.erb
    end
  end

  # GET /
  def new
    @paste = Paste.new
    @paste.set_paste_key
    begin
      @paste.paste = Paste.find(params[:base]).paste
    rescue
    end

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

  # POST /
  # POST /pastes.json
  # POST /pastes.txt
  def create
    @paste = Paste.new
    @paste.ip = request.remote_ip
    if params[:paste]
      if params[:paste][:paste_gzip_base64]
        # 1. decode from base64
        # 2. create StringIO from decoded string
        # 3. unzip and read the stream
        params[:paste][:paste] = Zlib::GzipReader.new(StringIO.new(Base64.decode64(params[:paste][:paste_gzip_base64]))).read
      end
      unless params[:paste][:paste].blank?
        @paste.paste = params[:paste][:paste]
      end
      if params[:paste][:key]
        @paste.key = params[:paste][:key]
      end
    end

    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
          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.find(params[:id].to_i)
    if @paste.key == params[:paste][:key]
      @paste.destroy
      expire_page :controller => 'pastes', :action => 'show', :id => @paste.id
      flash[:notice] = "Paste ##{params[:id]} deleted"
      redirect_to root_path
    else
      flash[:error] = 'Incorrect deletion key'
      render :action => :show
    end
  end

end