Sha256: b8c256c13db8a0891f76bf4371d995629e7a363504ff35b5337f24cc2bf6b382

Contents?: true

Size: 945 Bytes

Versions: 1

Compression:

Stored size: 945 Bytes

Contents

module PeoplePlacesThings
  class Location
    attr_accessor :city, :state, :zip, :raw
  
    def initialize(str)
      self.raw = str
    
      tokens = str.split(/\s|,/).collect { |t| t.strip }.reject { |t| t.length == 0 }
    
      # try to parse last token as zip
      #
      self.zip = ZipCode.new(tokens.last) rescue nil
      tokens = tokens.slice(0..-2) if self.zip
      
      # try to parse out the state (california, new york, district of columbia)
      #
      3.times do |i|
        self.state = State.new(tokens.last(i).join(" ")) rescue nil
        if self.state
          tokens = tokens.slice(0..(-1 - i))
          break
        end
      end
      
      # remainder must be city
      #
      self.city = tokens.join(' ').strip
      self.city = nil if self.city.empty?
    end
  
    def to_s
      [[self.city, (self.state.to_s(:abbr) rescue nil)].compact.join(','), self.zip.to_s].compact.join(' ')
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
people_places_things-2.5.1 lib/people_places_things/location.rb