class ChgkRating::Collections::Base

Attributes

items[R]

Public Class Methods

new(params = {}) click to toggle source
# File lib/chgk_rating/collections/base.rb, line 9
def initialize(params = {})
  results = params[:collection] ||
      prepare(get(api_path, build_request_params_from(params)))

  @items = process results, params
end

Public Instance Methods

[](index) click to toggle source
# File lib/chgk_rating/collections/base.rb, line 20
def [](index)
  @items[index]
end
convertable?(method) click to toggle source
# File lib/chgk_rating/collections/base.rb, line 43
def convertable?(method)
  return true if (method == :to_a && self.items.is_a?(Array)) ||
      (method == :to_h && self.items.is_a?(Hash))
  false
end
each() { |*item| ... } click to toggle source
# File lib/chgk_rating/collections/base.rb, line 16
def each
  @items.each { |item| yield(*item) }
end
respond_to?(method, include_all = false) click to toggle source
Calls superclass method
# File lib/chgk_rating/collections/base.rb, line 34
def respond_to?(method, include_all = false)
  method = method.to_sym
  if %i( to_a to_h ).include?(method.to_sym)
    self.convertable? method
  else
    super
  end
end
to_a() click to toggle source
# File lib/chgk_rating/collections/base.rb, line 24
def to_a
  raise ChgkRating::Error::NotArrayType unless self.respond_to?(:to_a)
  self.items.to_a.map &:to_h
end
to_h() click to toggle source
# File lib/chgk_rating/collections/base.rb, line 29
def to_h
  raise ChgkRating::Error::NotHashType unless self.respond_to?(:to_h)
  self.items.map { |k,v| revert_to_hash(k, v) }.to_h
end

Private Instance Methods

build_request_params_from(params) click to toggle source
# File lib/chgk_rating/collections/base.rb, line 55
def build_request_params_from(params)
  request_params = params[:request].to_h
  request_params[:page] = params.delete(:page).to_i if params.has_key?(:page)
  request_params
end
prepare(raw_results) click to toggle source
# File lib/chgk_rating/collections/base.rb, line 61
def prepare(raw_results)
  if raw_results.respond_to?(:has_key?)
    return raw_results['tournaments'] if raw_results.has_key?('tournaments')
    return raw_results['items'] if raw_results.has_key?('items')
  end

  raw_results
end
process(results, *_args) { |result| ... } click to toggle source
# File lib/chgk_rating/collections/base.rb, line 70
def process(results, *_args)
  if results.is_a? Hash
    results.each { |season, result| results[season] = yield result }
  else
    results.map { |result| yield result }
  end
end
revert_to_hash(key, values) click to toggle source
# File lib/chgk_rating/collections/base.rb, line 51
def revert_to_hash(key, values)
  [key, values.to_h]
end