Class: TwitterCldr::Parsers::NumberParser

Inherits:
Object
  • Object
show all
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

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

Returns:

  • (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

Raises:



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, options = {})
  options[:strict] = true unless options.include?(:strict)
  group, decimal = separators(options[: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, options = {})
  begin
    result = parse(number_text, options)
  rescue InvalidNumberError
    result = nil
  end

  if block_given?
    yield(result)
  else
    result || default
  end
end

#valid?(number_text, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


55
56
57
58
59
60
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 55

def valid?(number_text, options = {})
  parse(number_text, options)
  true
rescue
  false
end