Guest User

Untitled

a guest
May 23rd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. class NumericInputValue < ActiveRecord::Base
  2.  
  3. include InputValueBehaviour
  4.  
  5. DEFAULT_PRECISION = 2
  6.  
  7. NUMBER_PARSER = NumbersParser.new
  8.  
  9. # avoid default error message
  10. # schema_validations :except => :value
  11.  
  12. validates_numericality_of :value,
  13. :message => "Nur Zahlen sind erlaubt",
  14. :only_integer => true
  15.  
  16.  
  17. def precision
  18. has_value_specification? ? value_specification.precision : DEFAULT_PRECISION
  19. end
  20.  
  21. def numeric_input_ranges
  22. value_specification.numeric_input_ranges if has_value_specification?
  23. end
  24.  
  25. def has_numeric_input_ranges?
  26. not numeric_input_ranges.nil?
  27. end
  28.  
  29. def allowed?(value)
  30. if has_numeric_input_ranges?
  31. numeric_input_ranges.all? {|r| r.allows_value?(value) }
  32. else
  33. true
  34. end
  35. end
  36.  
  37.  
  38. def value=(v)
  39. write_attribute(:value, internal_value(v))
  40. end
  41.  
  42. def value
  43. precision == 0 ? external_value.to_i : external_value
  44. end
  45.  
  46.  
  47. def validate
  48. errors.add(:value, "#{error_message}") unless allowed?(value)
  49. end
  50.  
  51.  
  52.  
  53. private
  54.  
  55. # if the original value can't be parsed, return it and rely on
  56. # default exception and error message handling
  57. def internal_value(v)
  58. ast = NUMBER_PARSER.parse(v.to_s)
  59. ast ? (format("%0.#{precision}f", ast.eval).to_f * 10**precision).to_i : v
  60. end
  61.  
  62. def external_value
  63. read_attribute(:value).to_f / (10**precision)
  64. end
  65.  
  66. def error_message
  67. numeric_input_ranges.inject("") { |memo, range| memo << range.to_error_message }
  68. end
  69.  
  70. end
Add Comment
Please, Sign In to add comment