main_controller.rb 1009 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. require 'csv'
  2. class MainController < ApplicationController
  3. before_action :valify_event_key, only: [:save_data, :download_data]
  4. def home
  5. head :ok
  6. end
  7. def new_event_key
  8. @event_key = SecureRandom.hex
  9. File.open(data_path, "w+")
  10. render json: { event_key: @event_key}
  11. end
  12. def save_data
  13. hash = params.as_json.except('controller', 'action', 'event_key')
  14. CSV.open(data_path, 'ab') do |csv|
  15. return if hash.blank?
  16. csv << hash.keys if first_row?
  17. csv << hash.values
  18. end
  19. head :ok
  20. end
  21. def download_data
  22. send_file(data_path, filename: "#{@event_key}.csv", type: 'text/csv; charset=utf-8; header=present')
  23. end
  24. private
  25. def valify_event_key
  26. @event_key = params[:event_key]
  27. if @event_key.nil?
  28. head :forbidden && return
  29. elsif Dir.glob(data_path).blank?
  30. head :forbidden && return
  31. end
  32. end
  33. def first_row?
  34. File.size(data_path) == 0
  35. end
  36. def data_path
  37. Rails.root.join("storage/#{@event_key}.csv")
  38. end
  39. end