module Rancher::Classify

Convert Results into a Ruby Class

Public Instance Methods

classify(data) click to toggle source
# File lib/rancher/classify.rb, line 8
def classify(data)
  classify_recursive(data)
end

Private Instance Methods

classify_array(data, depth) click to toggle source
# File lib/rancher/classify.rb, line 51
def classify_array(data, depth)
  data.map { |element| classify_recursive(element, depth + 1) }
end
classify_object(data, depth) click to toggle source
# File lib/rancher/classify.rb, line 37
def classify_object(data, depth)
  data.each do |key, element|
    if element.is_a?(Array)
      data[key] = classify_array(element, depth + 1)
    elsif is_object?(element) && element[:type] && data.rels[key]
      data[key] = classify_object(element, depth + 1)
    elsif element.is_a?(Sawyer::Resource)
      data[key] = element.to_attrs
    end
  end

  get_class(data).new(data.attrs)
end
classify_recursive(data, depth = 0, as = 'auto') click to toggle source
# File lib/rancher/classify.rb, line 18
def classify_recursive(data, depth = 0, as = 'auto')
  as = classify_type(data) if as == 'auto'

  return classify_object(data, depth) if as == 'object'
  return classify_array(data, depth) if as == 'array'

  data
end
classify_type(data) click to toggle source
# File lib/rancher/classify.rb, line 27
def classify_type(data)
  if is_object?(data)
    return 'object'
  elsif data.is_a?(Array)
    return 'array'
  end

  'scalar'
end
get_class(data) click to toggle source
# File lib/rancher/classify.rb, line 55
def get_class(data)
  klass = Rancher::Resource

  if data[:type]
    klass = Rancher::Collection if data[:type] == 'collection'
    klass = Rancher::Error if data[:type] == 'error'
  end

  klass
end
is_object?(object) click to toggle source
# File lib/rancher/classify.rb, line 14
def is_object?(object)
  (object.is_a?(Sawyer::Resource) || object.is_a?(Hash))
end