lib/geo.rb in geo-lite-city-0.0.2 vs lib/geo.rb in geo-lite-city-0.0.3
- old
+ new
@@ -1,6 +1,7 @@
require "geoip"
+require "ensure/encoding"
module Geo
end
require "geo/instance"
@@ -21,13 +22,28 @@
end
end
private
+ def self.adjust_encoding(rec)
+ rec.inject({}) do |hsh, (key, value)|
+ if value.is_a?(String)
+ value = value.ensure_encoding('UTF-8',
+ :external_encoding => [Encoding::ISO8859_1, Encoding::UTF_8],
+ :invalid_characters => :transcode
+ )
+ end
+
+ hsh.update key => value
+ end
+ end
+
def self.complete_city(city)
city = city.to_hash
+ city = adjust_encoding(city)
+
parts = city.values_at :city_name, :region_name, :country_name
city_name = parts.grep(/[a-zA-Z]/).join(", ")
parts = city.values_at :continent_code, :country_code2, :region_name
region_code = parts.grep(/[a-zA-Z]/).join(".")
@@ -38,27 +54,23 @@
city.update name: city_name, region_code: region_code, country_code: country_code
end
public
- def self.cities(s, &block)
- expect! s => [ Regexp, /../ ]
+ def self.cities(pattern=nil, &block)
+ expect! pattern => [ nil, Regexp, String ]
- s = Regexp.compile("^" + Regexp.escape(s) + "$") unless s.is_a?(Regexp)
+ pattern = Regexp.compile("^" + Regexp.escape(pattern) + "$") if pattern.is_a?(String)
- quietly do
- r = []
+ ary = []
+ collect = block || ary.method(:push)
- instance.each.select do |rec|
- next if rec.city_name !~ s
-
- rec = complete_city(rec)
- yield rec if block
- r.push rec
- end
-
- r
+ instance.each do |rec|
+ next if pattern && rec.city_name !~ pattern
+ collect.call complete_city(rec)
end
+
+ block ? self : ary
end
private
# quietly and silence_stream are taken from activesupport