Juzmach/ohtu2015-jesh.io

View on GitHub
app/controllers/references_controller.rb

Summary

Maintainability
A
0 mins
Test Coverage
##
# Controller for Reference model

class ReferencesController < ApplicationController
  before_action :set_reference, only: [:show, :edit, :update, :destroy]
  before_action :set_types, only: [:new, :edit, :create, :update]

  # GET /references
  # GET /references.json
  # if search parameters have been entered, filter references to be shown
  def index
    if params[:search]
      @references = Reference.search(params[:search])
    else
      @references = Reference.all
    end
  end

  # GET /references/1
  # GET /references/1.json
  def show
  end

  # GET /references/new
  def new
    @reference = Reference.new
  end

  # GET /references/1/edit
  def edit
  end

  # POST /references
  # POST /references.json
  def create
    @reference = Reference.new(reference_params)

    respond_to do |format|
      if @reference.save
        format.html { redirect_to @reference, notice: 'Reference was successfully created.' }
        format.json { render :show, status: :created, location: @reference }
      else
        format.html { render :new }
        format.json { render json: @reference.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /references/1
  # PATCH/PUT /references/1.json
  def update
    respond_to do |format|
      if @reference.update(reference_params)
        format.html { redirect_to @reference, notice: 'Reference was successfully updated.' }
        format.json { render :show, status: :ok, location: @reference }
      else
        format.html { render :edit }
        format.json { render json: @reference.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /references/1
  # DELETE /references/1.json
  def destroy
    @reference.destroy
    respond_to do |format|
      format.html { redirect_to references_url, notice: 'Reference was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  # Export form calls references#export. Creates bibtex file and sends it to user.
  def export
      createbib(Reference.all)
      send_file 'public/export.bib'
  end



  private
    # Use callbacks to share common setup or constraints between actions.
    def set_reference
      @reference = Reference.find(params[:id])
    end
# Creates the export.bib file in the public folder by calling bibtexify for every reference.
  def createbib(references)
    open('public/export.bib', 'w') { |f|
      references.each do |reference|
        f.puts reference.bibtexify
      end
    }
  end

    # Initialize types
    def set_types
      @types = ["Book", "Article", "Inproceedings"]
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def reference_params
      params.require(:reference).permit(:reference_type, :author, :title, :year, :publisher)
    end
end