kube_schemaSourceKubeSchemaResource

class Resource

Definitions

def self.schema

Gets overridden by the factory in Kube::Schema::Instance

Implementation

def self.schema
  raise "Kube::Schema::Resource should NOT be instanciated directly"
end

def self.defaults

Gets overridden by the factory in Kube::Schema::Instance. Returns a frozen Hash like "apiVersion" => "apps/v1", "kind" => "Deployment"

Implementation

def self.defaults
  raise "Kube::Schema::Resource should NOT be instanciated directly"
end

def valid!

Like #valid? but raises Kube::ValidationError with details on failure. The error message includes the resource kind and name for context.

Implementation

def valid!
  if self.class.schema.nil?
    true
  else
    data = deep_stringify_keys(to_h)
    errors = self.class.schema.validate(data).to_a

    unless errors.empty?
      kind = self.class.defaults&.dig("kind")
      name = data.dig("metadata", "name")
      raise Kube::ValidationError.new(errors, kind: kind, name: name, manifest: data)
    end

    true
  end
end

def to_h

Returns the resource data as a Hash. Defaults (apiVersion, kind) from the schema are authoritative and cannot be overridden -- they are facts derived from the GVK metadata.

Implementation

def to_h
  defaults = self.class.defaults
  data = deep_compact(@data)
  data = data.reject { |_, v| v.is_a?(Hash) && v.empty? }

  if defaults
    symbolized = deep_symbolize_keys(defaults)
    # Defaults go first (for key ordering), then user data minus
    # any attempts to override the authoritative keys.
    symbolized.merge(data.reject { |k, _| symbolized.key?(k) })
  else
    data
  end
end

def to_yaml

Serializes to clean Kubernetes YAML. Raises Kube::ValidationError if the resource is not valid.

Implementation

def to_yaml
  if valid!
    deep_stringify_keys(to_h).to_yaml
  end
end