Class: Scjson::Types::DatamodelProps

Inherits:
Object
  • Object
show all
Defined in:
lib/scjson/types.rb

Overview

container for one or more ‘<data>` elements.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**kwargs) ⇒ DatamodelProps

Instantiate a new DatamodelProps object.

Parameters:

  • kwargs (Hash)

    Optional keyword overrides.



467
468
469
470
471
# File 'lib/scjson/types.rb', line 467

def initialize(**kwargs)
  @data = kwargs.fetch(:data, [])
  @other_element = kwargs.fetch(:other_element, [])
  @other_attributes = kwargs.fetch(:other_attributes, {})
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



464
465
466
# File 'lib/scjson/types.rb', line 464

def data
  @data
end

#other_attributesObject

Returns the value of attribute other_attributes.



464
465
466
# File 'lib/scjson/types.rb', line 464

def other_attributes
  @other_attributes
end

#other_elementObject

Returns the value of attribute other_element.



464
465
466
# File 'lib/scjson/types.rb', line 464

def other_element
  @other_element
end

Class Method Details

.from_hash(data) ⇒ DatamodelProps

Build an instance from a Hash representation.

Parameters:

  • data (Hash)

    Canonical hash representation.

Returns:

Raises:

  • (ArgumentError)


476
477
478
479
480
481
482
483
484
485
# File 'lib/scjson/types.rb', line 476

def self.from_hash(data)
  raise ArgumentError, 'Expected Hash' unless data.is_a?(Hash)

  normalized = data.transform_keys(&:to_s)
  kwargs = {}
  kwargs[:data] = Array(normalized.fetch('data', [])).map { |item| DataProps.from_hash(item) }
  kwargs[:other_element] = Array(normalized.fetch('other_element', []))
  kwargs[:other_attributes] = normalized.fetch('other_attributes', {})
  new(**kwargs)
end

.from_json(json) ⇒ DatamodelProps

Deserialize an instance from a JSON payload.

Parameters:

  • json (String)

    JSON document to decode.

Returns:



490
491
492
493
# File 'lib/scjson/types.rb', line 490

def self.from_json(json)
  parsed = JSON.parse(json)
  from_hash(parsed)
end

Instance Method Details

#to_hashHash

Convert the object to a Hash suitable for JSON serialization.

Returns:

  • (Hash)


497
498
499
500
501
502
503
# File 'lib/scjson/types.rb', line 497

def to_hash
  {
    'data' => (@data || []).map { |item| item.respond_to?(:to_hash) ? item.to_hash : item },
    'other_element' => @other_element,
    'other_attributes' => @other_attributes
  }
end

#to_json(*opts) ⇒ String

Serialize the object to JSON.

Parameters:

  • opts (Array)

    JSON generation options.

Returns:

  • (String)


508
509
510
# File 'lib/scjson/types.rb', line 508

def to_json(*opts)
  JSON.generate(to_hash, *opts)
end