Class: T2Airtime::Product

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

Class Method Summary collapse

Class Method Details

.all(operator_id) ⇒ Object



226
227
228
229
230
# File 'lib/t2_airtime/serializer.rb', line 226

def self.all(operator_id)
  Rails.cache.fetch("products/#{operator_id}", expires_in: 1.hour) do
    T2Airtime::API.api.product_list(operator_id)
  end
end

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



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/t2_airtime/serializer.rb', line 243

def self.serialize(data, ts = Time.zone.now.to_s, qty = 'all')
  return [] if data[:product_list].nil?
  ids = data[:product_list].split(',')
  retail_prices = data[:retail_price_list].split(',')
  wholesale_prices = data[:wholesale_price_list].split(',')
  Rails.cache.fetch("products/#{data[:operatorid]}/serializer", expires_in: 1.hour) do
    ids.take(qty==='all' ? ids.count : qty).each_with_index.map do |id, n|
      {
        type: 'products',
        id: Integer(id),
        attributes: {
          name: "#{Money.new(Integer(id) * 100, data[:destination_currency]).format}",
          localCurrency: data[:destination_currency],
          localCurrencySymbol: Money::Currency.new(data[:destination_currency]).symbol,
          currency: .currency,
          currencySymbol: Money::Currency.new(.currency).symbol,
          localPrice: Float(id),
          retailPrice: Float(retail_prices[n]),
          wholesalePrice: Float(wholesale_prices[n]),
          countryId: Integer(data[:countryid]), 
          countryName: data[:country],
          countryAlpha3: T2Airtime::Country.alpha3(data[:country]),
          operatorId: Integer(data[:operatorid]),
          operatorName: data[:operator],
          operatorLogo: T2Airtime::Util.operator_logo_url(data[:operatorid]),                      
          fetchedAt: T2Airtime::Util.format_time(ts)
        },
        relationships: {
          country: {
            data: {
              type: 'countries',
              id: Integer(data[:countryid])
            }
          },
          operator: {
            data: {
              type: 'operators',
              id: Integer(data[:operatorid])
            }
          }
        }
      }
    end
  end
end

.take(qty = 5, operator_qty = 1, country_qty = 1) ⇒ Object



232
233
234
235
236
237
238
239
240
241
# File 'lib/t2_airtime/serializer.rb', line 232

def self.take(qty = 5, operator_qty = 1, country_qty = 1)
  operators = T2Airtime::Operator.take(operator_qty, country_qty).shuffle
  unless operators.empty?
    operators.flat_map do |operator| (          
      products = all(operator[:id])
      products.success? ? serialize(products.data, products.headers[:date], qty) : []
    )
    end
  end
end