Class: DockerSwarm::Base

Inherits:
Object
  • Object
show all
Includes:
ActiveModel::Model, Concerns::Inspectable
Defined in:
lib/docker_swarm/base.rb

Direct Known Subclasses

Config, Container, Image, Network, Node, Secret, Service, Swarm, System, Task, Volume

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Concerns::Inspectable

#inspect

Constructor Details

#initialize(attributes = {}) ⇒ Base

Returns a new instance of Base.



90
91
92
93
# File 'lib/docker_swarm/base.rb', line 90

def initialize(attributes = {})
  assign_attributes(attributes) if attributes.present?
  super()
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/docker_swarm/base.rb', line 150

def method_missing(method_name, *args, &block)
  method_str = method_name.to_s

  if method_str.end_with?("=")
    _define_dynamic_accessor(method_str.chomp("="))
    instance_variable_set("@#{method_str.chomp('=')}", args.first)
  elsif _valid_attribute_name?(method_str) && instance_variable_defined?("@#{method_str}")
    instance_variable_get("@#{method_str}")
  elsif !method_str.end_with?("?")
    _define_dynamic_accessor(method_str)
    nil
  else
    super
  end
end

Class Method Details

.all(filters = {}) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/docker_swarm/base.rb', line 30

def all(filters = {})
  response = _fetch_all(filters)
  return [] if response.blank?

  data = root_key && response.is_a?(Hash) ? response[root_key] : response
  Array(data).map { |item| new(item) }
end

.defined_attributesSet

Cache of attributes already defined for this class

Returns:

  • (Set)


15
16
17
# File 'lib/docker_swarm/base.rb', line 15

def defined_attributes
  @defined_attributes ||= Set.new([ :validation_context, :errors, :context_for_validation ])
end

.find(id) ⇒ Object



38
39
40
41
42
43
# File 'lib/docker_swarm/base.rb', line 38

def find(id)
  data = Api.request(action: routes[:show], arguments: { id: id })
  new(data)
rescue Errors::NotFound
  nil
end

.index_query_paramsArray<Symbol>

Claves que el Engine toma como query params propios del listado (?limit=, ?all=, …), no como filters.

Todo lo que NO esté declarado acá se serializa dentro del JSON de ?filters=. Si además no es un filtro válido del recurso, el Engine lo rechaza o lo ignora: el parámetro no llega y no hay forma de pedirlo desde la gema.

Override en el modelo que declare uno propio (p. ej. status en Service). La lista no se generaliza acá por comodidad: un mismo nombre puede ser query param en un recurso y filtro legítimo en otro (status lo es en /containers/json), y globalizarlo lo saca del ?filters= donde ese otro recurso lo necesita.

Returns:

  • (Array<Symbol>)

    nombres de query param



63
64
65
# File 'lib/docker_swarm/base.rb', line 63

def index_query_params
  %i[all force limit since before].freeze
end

.resource_nameObject



9
10
11
# File 'lib/docker_swarm/base.rb', line 9

def resource_name
  name.demodulize.downcase.pluralize
end

.root_keyString?

Key in the JSON response that contains the array of items. Override in subclasses if the API returns a wrapped object (e.g., Volumes).

Returns:

  • (String, nil)


26
27
28
# File 'lib/docker_swarm/base.rb', line 26

def root_key
  nil
end

.routesObject



19
20
21
# File 'lib/docker_swarm/base.rb', line 19

def routes
  Api::ENDPOINTS[resource_name.to_sym]
end

.where(filters) ⇒ Object



45
46
47
# File 'lib/docker_swarm/base.rb', line 45

def where(filters)
  all(filters)
end

Instance Method Details

#as_json(options = nil) ⇒ Object



124
125
126
# File 'lib/docker_swarm/base.rb', line 124

def as_json(options = nil)
  serializable_hash(options)
end

#assign_attributes(new_attributes) ⇒ Object

Raises:

  • (ArgumentError)


95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/docker_swarm/base.rb', line 95

def assign_attributes(new_attributes)
  return if new_attributes.blank?
  raise ArgumentError, "assign_attributes expects a Hash, got #{new_attributes.class}" unless new_attributes.is_a?(Hash)

  attributes_to_assign = new_attributes.deep_dup.with_indifferent_access
  normalized_attributes = {}

  attributes_to_assign.each do |key, value|
    normalized_key = key.to_s == "Id" ? "ID" : key.to_s
    _define_dynamic_accessor(normalized_key)

    if normalized_key == "Spec" && respond_to?(:Spec) && self.Spec.is_a?(Hash) && value.is_a?(Hash)
      value = self.Spec.deep_merge(value)
    end

    normalized_attributes[normalized_key] = value
  end

  super(normalized_attributes)
end

#attributesObject



116
117
118
# File 'lib/docker_swarm/base.rb', line 116

def attributes
  instance_values.except("validation_context", "errors", "context_for_validation")
end

#idObject



140
141
142
# File 'lib/docker_swarm/base.rb', line 140

def id
  self.ID
end

#payload_for_dockerObject



128
129
130
131
132
133
134
# File 'lib/docker_swarm/base.rb', line 128

def payload_for_docker
  data = attributes.except("ID", "Id", "Version", "CreatedAt", "UpdatedAt").compact
  return data unless data.key?("Spec")

  spec = data.delete("Spec").deep_dup
  spec.merge!(data)
end

#persisted?Boolean

Returns:

  • (Boolean)


136
137
138
# File 'lib/docker_swarm/base.rb', line 136

def persisted?
  respond_to?(:ID) && self.ID.present?
end

#reloadObject



144
145
146
147
148
# File 'lib/docker_swarm/base.rb', line 144

def reload
  fresh = self.class.find(id)
  assign_attributes(fresh.attributes) if fresh
  self
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


166
167
168
169
170
171
172
# File 'lib/docker_swarm/base.rb', line 166

def respond_to_missing?(method_name, include_private = false)
  method_str = method_name.to_s
  method_str.end_with?("=") ||
    (_valid_attribute_name?(method_str) && instance_variable_defined?("@#{method_str}")) ||
    (!method_str.end_with?("?") && _valid_attribute_name?(method_str)) ||
    super
end

#serializable_hash(_options = nil) ⇒ Object



120
121
122
# File 'lib/docker_swarm/base.rb', line 120

def serializable_hash(_options = nil)
  attributes
end