Module: Spaceship::ConnectAPI::Model

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#idObject

Returns the value of attribute id.



10
11
12
# File 'spaceship/lib/spaceship/connect_api/model.rb', line 10

def id
  @id
end

#reverse_attr_mapObject

Returns the value of attribute reverse_attr_map.



11
12
13
# File 'spaceship/lib/spaceship/connect_api/model.rb', line 11

def reverse_attr_map
  @reverse_attr_map
end

Class Method Details

.included(base) ⇒ Object



4
5
6
7
8
# 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

Instance Method Details

#attr_mapping(attr_map) ⇒ Object

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

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



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 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

#initialize(id, attributes) ⇒ Object



13
14
15
16
# File 'spaceship/lib/spaceship/connect_api/model.rb', line 13

def initialize(id, attributes)
  self.id = id
  update_attributes(attributes)
end

#reverse_attr_mapping(attributes) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
# 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) ⇒ Object



67
68
69
70
71
# 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) ⇒ Object



18
19
20
21
22
23
# 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