test_controller.rb 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. #---
  10. # Excerpted from "Agile Web Development with Rails, 4rd Ed.",
  11. # published by The Pragmatic Bookshelf.
  12. # Copyrights apply to this code. It may not be used to create training material,
  13. # courses, books, articles, and the like. Contact us if you are in doubt.
  14. # We make no guarantees that this code is fit for any purpose.
  15. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  16. #---
  17. class TestController < ApplicationController
  18. def rdoc
  19. @value = 123
  20. end
  21. def date_dump
  22. end
  23. def calculate
  24. if request.post?
  25. @errors = []
  26. arg1 = convert_float(:arg1)
  27. arg2 = convert_float(:arg2)
  28. op = convert_operator(:operator)
  29. if @errors.empty?
  30. begin
  31. @result = op.call(arg1, arg2)
  32. rescue Exception => err
  33. @result = err.message
  34. end
  35. end
  36. end
  37. end
  38. private
  39. def convert_float(name)
  40. if params[name].blank?
  41. @errors << "#{name} missing"
  42. else
  43. begin
  44. Float(params[name])
  45. rescue Exception => err
  46. @errors << "#{name}: #{err.message}"
  47. nil
  48. end
  49. end
  50. end
  51. def convert_operator(name)
  52. case params[name]
  53. when "+" then proc {|a,b| a+b}
  54. when "-" then proc {|a,b| a-b}
  55. when "*" then proc {|a,b| a*b}
  56. when "/" then proc {|a,b| a/b}
  57. else
  58. @errors << "Missing or invalid operator"
  59. nil
  60. end
  61. end
  62. end