Class: Kube::Schema::Resource

Inherits:
Object
  • Object
show all
Defined in:
lib/kube/schema/resource.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash = {}, &block) ⇒ Resource

Subclasses generated by Instance#[] have a class-level .schema which is a JSONSchemer::Schema object, and .defaults which provides apiVersion and kind derived from the GVK metadata.



12
13
14
15
16
17
# File 'lib/kube/schema/resource.rb', line 12

def initialize(hash = {}, &block)
  hash = deep_stringify_keys(hash)

  @data = BlackHoleStruct.new(hash)
  @data.instance_exec(&block) if block
end

Class Method Details

.defaultsObject

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



26
27
28
# File 'lib/kube/schema/resource.rb', line 26

def self.defaults
  nil
end

.schemaObject

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



20
21
22
# File 'lib/kube/schema/resource.rb', line 20

def self.schema
  nil
end

Instance Method Details

#==(other) ⇒ Object



77
78
79
# File 'lib/kube/schema/resource.rb', line 77

def ==(other)
  other.is_a?(Resource) && to_h == other.to_h
end

#to_hObject

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.



56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/kube/schema/resource.rb', line 56

def to_h
  defaults = self.class.defaults
  data = @data.to_h

  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

#to_yamlObject

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



72
73
74
75
# File 'lib/kube/schema/resource.rb', line 72

def to_yaml
  valid!
  deep_stringify_keys(to_h).to_yaml
end

#valid!Object

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



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/kube/schema/resource.rb', line 38

def valid!
  return true if self.class.schema.nil?

  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

#valid?Boolean

Returns:

  • (Boolean)


30
31
32
33
34
# File 'lib/kube/schema/resource.rb', line 30

def valid?
  return true if self.class.schema.nil?

  self.class.schema.valid?(deep_stringify_keys(to_h))
end