Class: OpenActive::Helpers::JsonLd

Inherits:
Object
  • Object
show all
Defined in:
lib/openactive/helpers/json_ld.rb

Class Method Summary collapse

Class Method Details

.get_type(thing) ⇒ string

Returns the JSON-LD type from a given thing.

Parameters:

Returns:

  • (string)


9
10
11
12
13
14
15
# File 'lib/openactive/helpers/json_ld.rb', line 9

def get_type(thing)
  # Append "type" attribute for all other classes
  reflect = ::ReflectionClass.new(thing)

  # Type is just the non-FQ class name
  reflect.get_short_name
end

.prepare_data_for_serialization(obj, parent = nil, schema: false) ⇒ array

Returns an associative array with the data ready for JSON-LD serialization.

Parameters:

  • obj (::OpenActive::JsonLdModel)

    The given instance to convert to JSON-LD

  • parent (object, null) (defaults to: nil)

    The parent node in the structure.

Returns:

  • (array)


22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/openactive/helpers/json_ld.rb', line 22

def prepare_data_for_serialization(obj, parent = nil, schema: false)
  data = obj.values

  # Only add context if object is subclass of BaseModel
  # and no parent, or parent is an RPDE item
  if obj.respond_to?(:context) && (parent.nil? || !parent.is_a?(OpenActive::JsonLdModel))

    data["@context"] =
      [
        *obj.context,
        *(schema ? ["https://schema.org"] : [])
      ]
  end

  # Loop all class methods, find the getters
  # and map defined attributes, normalizing attribute name
  data = Hash[data.map do |method_name, attr_value|
    attr_name = method_name

    attr_value = serialize_value(attr_value, obj, schema: schema)

    [attr_name.to_s, attr_value]
  end]

  # Remove empty elements
  Hash[data.select do |_key, value|
    next false if value.is_a?(Array) && value.empty?
    next false if value.nil?
    next false if value == ""

    true
  end]
end

.serialize_value(value, parent = nil, **kwargs) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/openactive/helpers/json_ld.rb', line 56

def serialize_value(value, parent = nil, **kwargs)
  if value.respond_to?(:iso8601)
    value.iso8601
  elsif value.is_a?(TypesafeEnum::Base)
    value.value
  elsif value.is_a?(Array)
    value.map do |item|
      serialize_value(item, parent, **kwargs)
    end
  elsif value.is_a?(OpenActive::BaseModel)
    prepare_data_for_serialization(
      value,
      parent,
      **kwargs,
    )
  elsif value.is_a?(Numeric)
    value
  elsif value.nil? # let nil be nil
    nil
  else
    value.to_s
  end
end