module Spaceship::ConnectAPI::Model

Attributes

id[RW]
reverse_attr_map[RW]

Public Class Methods

included(base) click to toggle source
# File spaceship/lib/spaceship/connect_api/model.rb, line 4
def self.included(base)
  Spaceship::ConnectAPI::Models.types ||= []
  Spaceship::ConnectAPI::Models.types << base
  base.extend(Spaceship::ConnectAPI::Model)
end
new(id, attributes) click to toggle source
# File spaceship/lib/spaceship/connect_api/model.rb, line 13
def initialize(id, attributes)
  self.id = id
  update_attributes(attributes)
end

Public Instance Methods

attr_mapping(attr_map) click to toggle source

Example: { “minOsVersion” => “min_os_version” }

Creates attr_write and attr_reader for :min_os_version Creates alias for :minOsVersion to :min_os_version

# File spaceship/lib/spaceship/connect_api/model.rb, line 32
def attr_mapping(attr_map)
  self.reverse_attr_map ||= attr_map.invert.transform_keys(&:to_sym)
  attr_map.each do |key, value|
    # Actual
    reader = value.to_sym
    writer = "#{value}=".to_sym

    has_reader = instance_methods.include?(reader)
    has_writer = instance_methods.include?(writer)

    send(:attr_reader, value) unless has_reader
    send(:attr_writer, value) unless has_writer

    # Alias
    key_reader = key.to_sym
    key_writer = "#{key}=".to_sym

    # Alias the API response name to attribute name
    alias_method(key_reader, reader)
    alias_method(key_writer, writer)
  end
end
reverse_attr_mapping(attributes) click to toggle source
# File spaceship/lib/spaceship/connect_api/model.rb, line 55
def reverse_attr_mapping(attributes)
  return nil if attributes.nil?

  # allows for getting map from either an instance or class execution
  map = self.reverse_attr_map || self.class.reverse_attr_map

  attributes.each_with_object({}) do |(k, v), memo|
    key = map[k.to_sym] || k.to_sym
    memo[key] = v
  end
end
to_json(*options) click to toggle source
# File spaceship/lib/spaceship/connect_api/model.rb, line 67
def to_json(*options)
  instance_variables.map do |var|
    [var.to_s[1..-1], instance_variable_get(var)]
  end.to_h.to_json(*options)
end
update_attributes(attributes) click to toggle source
# File spaceship/lib/spaceship/connect_api/model.rb, line 18
def update_attributes(attributes)
  (attributes || []).each do |key, value|
    method = "#{key}=".to_sym
    self.send(method, value) if self.respond_to?(method)
  end
end