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