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) ⇒ NumberParser

Returns a new instance of NumberParser.



17
18
19
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 17

def initialize(locale = TwitterCldr.locale)
  @locale = locale
end

Class Method Details

.is_numeric?(text, separators = SEPARATOR_CHARS) ⇒ Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 59

def self.is_numeric?(text, separators = SEPARATOR_CHARS)
  !!(text =~ /\A[0-9#{separators}]+\Z/)
end

Instance Method Details

#parse(number_text, options = {}) ⇒ Object

Raises:



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 21

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



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 38

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)


52
53
54
55
56
57
# File 'lib/twitter_cldr/parsers/number_parser.rb', line 52

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