class Parsenum::Parser

Attributes

source[R]
type[R]
value[R]

Public Class Methods

new(source, type=nil) click to toggle source
# File lib/parsenum/parser.rb, line 4
def initialize(source, type=nil)
  @source = source
  @value = nil
  @type = nil
  run
end

Public Instance Methods

currency() click to toggle source
# File lib/parsenum/parser.rb, line 11
def currency
  return nil unless type == Parsenum::CURRENCY
  return 'GBP' if @source =~ /£/
  return 'USD' if @source =~ /\$/
  "other"
end
currency?() click to toggle source
# File lib/parsenum/parser.rb, line 26
def currency?
  @type == Parsenum::CURRENCY
end
float?() click to toggle source
# File lib/parsenum/parser.rb, line 30
def float?
  @type == Parsenum::FLOAT
end
integer?() click to toggle source
# File lib/parsenum/parser.rb, line 34
def integer?
  @type == Parsenum::INTEGER
end
nil?() click to toggle source
# File lib/parsenum/parser.rb, line 18
def nil?
  @type == Parsenum::NIL
end
percentage?() click to toggle source
# File lib/parsenum/parser.rb, line 22
def percentage?
  @type == Parsenum::PERCENTAGE
end

Private Instance Methods

estimate_type(str) click to toggle source
# File lib/parsenum/parser.rb, line 45
def estimate_type(str)
  return Parsenum::NIL        if str.nil?
  return Parsenum::PERCENTAGE if str =~ /%/
  return Parsenum::CURRENCY   if str =~ /\$|£/
  return Parsenum::FLOAT      if str =~ /\d\.\d/
  return Parsenum::INTEGER    if str =~ /\d/
  Parsenum::NIL
end
extract(str, t=nil) click to toggle source
# File lib/parsenum/parser.rb, line 54
def extract(str, t=nil)
  t ||= estimate_type(str)
  self.send(:"extract_#{t}", str)
end
extract_currency(str) click to toggle source
# File lib/parsenum/parser.rb, line 76
def extract_currency(str)
  matches = str.match(/(\$|£)([\d\,\.]+)/)
  return 0 unless matches
  extract(matches[2])
end
extract_float(str) click to toggle source
# File lib/parsenum/parser.rb, line 67
def extract_float(str)
  strip_commas(str).to_f
end
extract_integer(str) click to toggle source
# File lib/parsenum/parser.rb, line 63
def extract_integer(str)
  strip_commas(str).to_i
end
extract_nil(str) click to toggle source
# File lib/parsenum/parser.rb, line 59
def extract_nil(str)
  nil
end
extract_percentage(str) click to toggle source
# File lib/parsenum/parser.rb, line 71
def extract_percentage(str)
  str = str.sub('%', '')
  extract_float(str) / 100.0
end
run() click to toggle source
# File lib/parsenum/parser.rb, line 40
def run
  @type ||= estimate_type(@source)
  @value = extract(@source, @type)
end
strip_commas(str) click to toggle source
# File lib/parsenum/parser.rb, line 83
def strip_commas(str)
  str.gsub(',', '')
end