| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- require './lib/pkparse/client'
- class PokemonController < ApplicationController
- def index
- @pokemon = Pokemon.all
- end
- def show
- @pokemon = Pokemon.find(params[:id])
- end
- def new
- @pokemon = Pokemon.new
- end
- def create
- @pokemon = Pokemon.new(new_pokemon_params)
- if @pokemon.save
- redirect_to pokemon_path(@pokemon)
- else
- render :new
- end
- end
- def destroy
- pokemon = Pokemon.find(params[:id])
- if pokemon.destroy
- flash.now[:notice] = "Pokemon successfuly deleted."
- redirect_to pokemon_index_path
- else
- flash.now[:alert] = "Failed to delete pokemon."
- render :show
- end
- end
- def upload
- files = params[:pokemon]
- response = pkparse.parse(files)
- Pokemon.transaction do
- Pokemon.create!(response.pokemon.map(&:to_h))
- end
- redirect_to pokemon_index_path
- rescue PKParse::Error => e
- flash.now[:alert] = e.message
- @pokemon = Pokemon.new
- render :new
- rescue ActiveRecord::ActiveRecordError => e
- PKParse.logger.error("Failed to commit parsed results:\n#{e}\n#{e.backtrace.join("\n")}")
- flash.now[:alert] = "Failed to commit the uploaded pokemon."
- @pokemon = Pokemon.new
- render :new
- end
- private
- def new_pokemon_params
- params.require(:pokemon).permit(
- :id, :pokedex_number, :nickname
- )
- end
- def pkparse
- # There may be some configuration we'll provide in the future that would
- # benefit from instantiating the client in this way
- @pkparse_client ||= PKParse::Client.new
- end
- end
|