Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class NumericInputValue < ActiveRecord::Base
- include InputValueBehaviour
- DEFAULT_PRECISION = 2
- NUMBER_PARSER = NumbersParser.new
- # avoid default error message
- # schema_validations :except => :value
- validates_numericality_of :value,
- :message => "Nur Zahlen sind erlaubt",
- :only_integer => true
- def precision
- has_value_specification? ? value_specification.precision : DEFAULT_PRECISION
- end
- def numeric_input_ranges
- value_specification.numeric_input_ranges if has_value_specification?
- end
- def has_numeric_input_ranges?
- not numeric_input_ranges.nil?
- end
- def allowed?(value)
- if has_numeric_input_ranges?
- numeric_input_ranges.all? {|r| r.allows_value?(value) }
- else
- true
- end
- end
- def value=(v)
- write_attribute(:value, internal_value(v))
- end
- def value
- precision == 0 ? external_value.to_i : external_value
- end
- def validate
- errors.add(:value, "#{error_message}") unless allowed?(value)
- end
- private
- # if the original value can't be parsed, return it and rely on
- # default exception and error message handling
- def internal_value(v)
- ast = NUMBER_PARSER.parse(v.to_s)
- ast ? (format("%0.#{precision}f", ast.eval).to_f * 10**precision).to_i : v
- end
- def external_value
- read_attribute(:value).to_f / (10**precision)
- end
- def error_message
- numeric_input_ranges.inject("") { |memo, range| memo << range.to_error_message }
- end
- end
Add Comment
Please, Sign In to add comment