Class: T2Airtime::Country

Inherits:
Object
  • Object
show all
Defined in:
lib/t2_airtime/serializer.rb

Class Method Summary collapse

Class Method Details

.allObject



36
37
38
39
40
# File 'lib/t2_airtime/serializer.rb', line 36

def self.all
  Rails.cache.fetch('countries', expires_in: 1.hour) do
    T2Airtime::API.api.country_list
  end
end

.alpha3(name) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/t2_airtime/serializer.rb', line 70

def self.alpha3(name)
  alpha3 = ISO3166::Country.find_country_by_name(name).try(:alpha3)
  unless alpha3
    alpha3 = case name
             when 'Saint Vincent Grenadines'
               'VCT'
             when 'Kosovo'
               'UNK'
             when 'Netherlands Antilles'
               'ANT'
             when 'Serbia and Montenegro'
               'SCG'
    end
    register_alpha3(alpha3, name) if %w[VCT UNK ANT SCG].include?(alpha3)
  end
  alpha3 || 'XXX'
end

.normalize(name) ⇒ Object



66
67
68
# File 'lib/t2_airtime/serializer.rb', line 66

def self.normalize(name)
  name.starts_with?('St') ? name.gsub('St', 'Saint') : name
end

.register_alpha3(alpha3, name) ⇒ Object



88
89
90
91
92
93
94
# File 'lib/t2_airtime/serializer.rb', line 88

def self.register_alpha3(alpha3, name)
  ISO3166::Data.register(
    alpha2: 'XX',
    alpha3: alpha3,
    name: name
  )
end

.serialize(data, ts = Time.zone.now.to_s, qty = nil) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/t2_airtime/serializer.rb', line 47

def self.serialize(data, ts = Time.zone.now.to_s, qty = nil)
  return [] if data[:countryid].nil?
  names = data[:country].split(',')
  ids = data[:countryid].split(',')
  Rails.cache.fetch('countries/serializer', expires_in: 1.hour) do
    ids.take(qty.nil? ? ids.count : qty).each_with_index.map do |id, n|
      {
        type: 'countries',
        id: Integer(id),
        attributes: {
          name: names[n],
          alpha3: alpha3(names[n]),
          fetchedAt: T2Airtime::Util.format_time(ts)
        }
      }
    end
  end
end

.take(qty = 5) ⇒ Object



42
43
44
45
# File 'lib/t2_airtime/serializer.rb', line 42

def self.take(qty = 5)
  countries = all
  countries.success? ? serialize(countries.data, countries.headers[:date], qty) : []
end