Class: TwitterCldr::Parsers::NumberParser
- Inherits:
-
Object
- Object
- TwitterCldr::Parsers::NumberParser
- Defined in:
- lib/twitter_cldr/parsers/number_parser.rb
Constant Summary collapse
- SEPARATOR_CHARS =
['.', ',', ' '].map do |char| char == ' ' ? '\s' : Regexp.escape(char) end.join
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(locale = TwitterCldr.locale, number_system = nil) ⇒ NumberParser
constructor
A new instance of NumberParser.
- #parse(number_text, options = {}) ⇒ Object
- #try_parse(number_text, default = nil, options = {}) ⇒ Object
- #valid?(number_text, options = {}) ⇒ Boolean
Constructor Details
#initialize(locale = TwitterCldr.locale, number_system = nil) ⇒ NumberParser
Returns a new instance of NumberParser.
17 18 19 20 21 22 |
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 17 def initialize(locale = TwitterCldr.locale, number_system = nil) @locale = locale @data_reader = TwitterCldr::DataReaders::NumberDataReader.new( locale, number_system: number_system ) end |
Class Method Details
.is_numeric?(text, separators = SEPARATOR_CHARS) ⇒ Boolean
62 63 64 |
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 62 def self.is_numeric?(text, separators = SEPARATOR_CHARS) !!(text =~ /\A[0-9#{separators}]+\Z/) end |
Instance Method Details
#parse(number_text, options = {}) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 24 def parse(number_text, = {}) [:strict] = true unless .include?(:strict) group, decimal = separators([:strict]) tokens = tokenize(number_text, group, decimal) num_list, punct_list = tokens.partition { |t| t[:type] == :numeric } raise InvalidNumberError unless punct_valid?(punct_list) raise InvalidNumberError unless tokens.last && tokens.last[:type] == :numeric if punct_list.last && punct_list.last[:type] == :decimal result = num_list[0..-2].map { |num| num[:value] }.join.to_i result + num_list.last[:value].to_i / (10.0 ** num_list.last[:value].size) else num_list.map { |num| num[:value] }.join.to_i end end |
#try_parse(number_text, default = nil, options = {}) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 41 def try_parse(number_text, default = nil, = {}) begin result = parse(number_text, ) rescue InvalidNumberError result = nil end if block_given? yield(result) else result || default end end |
#valid?(number_text, options = {}) ⇒ Boolean
55 56 57 58 59 60 |
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 55 def valid?(number_text, = {}) parse(number_text, ) true rescue false end |