pokemon_controller.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. require './lib/pkparse/client'
  2. class PokemonController < ApplicationController
  3. def index
  4. @pokemon = Pokemon.all
  5. end
  6. def show
  7. @pokemon = Pokemon.find(params[:id])
  8. end
  9. def new
  10. @pokemon = Pokemon.new
  11. end
  12. def create
  13. @pokemon = Pokemon.new(new_pokemon_params)
  14. if @pokemon.save
  15. redirect_to pokemon_path(@pokemon)
  16. else
  17. render :new
  18. end
  19. end
  20. def destroy
  21. pokemon = Pokemon.find(params[:id])
  22. if pokemon.destroy
  23. flash.now[:notice] = "Pokemon successfuly deleted."
  24. redirect_to pokemon_index_path
  25. else
  26. flash.now[:alert] = "Failed to delete pokemon."
  27. render :show
  28. end
  29. end
  30. def upload
  31. files = params[:pokemon]
  32. response = pkparse.parse(files)
  33. Pokemon.transaction do
  34. Pokemon.create!(response.pokemon.map(&:to_h))
  35. end
  36. redirect_to pokemon_index_path
  37. rescue PKParse::Error => e
  38. flash.now[:alert] = e.message
  39. @pokemon = Pokemon.new
  40. render :new
  41. rescue ActiveRecord::ActiveRecordError => e
  42. PKParse.logger.error("Failed to commit parsed results:\n#{e}\n#{e.backtrace.join("\n")}")
  43. flash.now[:alert] = "Failed to commit the uploaded pokemon."
  44. @pokemon = Pokemon.new
  45. render :new
  46. end
  47. private
  48. def new_pokemon_params
  49. params.require(:pokemon).permit(
  50. :id, :pokedex_number, :nickname
  51. )
  52. end
  53. def pkparse
  54. # There may be some configuration we'll provide in the future that would
  55. # benefit from instantiating the client in this way
  56. @pkparse_client ||= PKParse::Client.new
  57. end
  58. end