Class: T2Airtime::Country

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

Class Method Summary collapse

Class Method Details

.allObject



103
104
105
106
107
# File 'lib/t2_airtime/serializer.rb', line 103

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

.alpha3(name) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
# File 'lib/t2_airtime/serializer.rb', line 138

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

.calling_code(alpha3) ⇒ Object



164
165
166
167
168
169
170
171
172
# File 'lib/t2_airtime/serializer.rb', line 164

def self.calling_code(alpha3)  
  country_code = case alpha3
      when 'PCN'
        '64'
      when 'ATF'
        '262'            
  end
  country_code || ISO3166::Country.find_country_by_alpha3(alpha3).try(:country_code)       
end

.normalize(name) ⇒ Object



134
135
136
# File 'lib/t2_airtime/serializer.rb', line 134

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

.register_alpha3(alpha3, name) ⇒ Object



156
157
158
159
160
161
162
# File 'lib/t2_airtime/serializer.rb', line 156

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 = 'all') ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/t2_airtime/serializer.rb', line 114

def self.serialize(data, ts = Time.zone.now.to_s, qty = 'all')
  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==='all' ? ids.count : qty).each_with_index.map do |id, n|
      {
        type: 'countries',
        id: Integer(id),
        attributes: {
          name: names[n],
          alpha3: alpha3(names[n]),
          callingCode: calling_code(alpha3(names[n])),
          fetchedAt: T2Airtime::Util.format_time(ts)
        }
      }
    end
  end
end

.take(qty = 5) ⇒ Object



109
110
111
112
# File 'lib/t2_airtime/serializer.rb', line 109

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